bug-ungetc2.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. static int
  4. check (FILE *fp, off_t o)
  5. {
  6. int result = 0;
  7. if (feof (fp))
  8. {
  9. puts ("feof !");
  10. result = 1;
  11. }
  12. if (ferror (fp))
  13. {
  14. puts ("ferror !");
  15. result = 1;
  16. }
  17. if (ftello (fp) != o)
  18. {
  19. printf ("position = %lu, not %lu\n", (unsigned long int) ftello (fp),
  20. (unsigned long int) o);
  21. result = 1;
  22. }
  23. return result;
  24. }
  25. static int
  26. do_test (void)
  27. {
  28. FILE *fp = tmpfile ();
  29. if (fp == NULL)
  30. {
  31. puts ("tmpfile failed");
  32. return 1;
  33. }
  34. if (check (fp, 0) != 0)
  35. return 1;
  36. puts ("going to write");
  37. if (fputs ("hello", fp) == EOF)
  38. {
  39. puts ("fputs failed");
  40. return 1;
  41. }
  42. if (check (fp, 5) != 0)
  43. return 1;
  44. puts ("going to rewind");
  45. rewind (fp);
  46. if (check (fp, 0) != 0)
  47. return 1;
  48. puts ("going to read char");
  49. int c = fgetc (fp);
  50. if (c != 'h')
  51. {
  52. printf ("read %c, not %c\n", c, 'h');
  53. return 1;
  54. }
  55. if (check (fp, 1) != 0)
  56. return 1;
  57. puts ("going to put back");
  58. if (ungetc (' ', fp) == EOF)
  59. {
  60. puts ("ungetc failed");
  61. return 1;
  62. }
  63. if (check (fp, 0) != 0)
  64. return 1;
  65. puts ("going to write again");
  66. if (fputs ("world", fp) == EOF)
  67. {
  68. puts ("2nd fputs failed");
  69. return 1;
  70. }
  71. if (check (fp, 5) != 0)
  72. return 1;
  73. puts ("going to rewind again");
  74. rewind (fp);
  75. if (check (fp, 0) != 0)
  76. return 1;
  77. if (fclose (fp) != 0)
  78. {
  79. puts ("fclose failed");
  80. return 1;
  81. }
  82. return 0;
  83. }
  84. #define TEST_FUNCTION do_test ()
  85. #include "../test-skeleton.c"