bug-ungetc3.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* Test program for ungetc/ftell interaction bug. */
  2. #include <stdio.h>
  3. static void do_prepare (void);
  4. #define PREPARE(argc, argv) do_prepare ()
  5. static int do_test (void);
  6. #define TEST_FUNCTION do_test ()
  7. #include "../test-skeleton.c"
  8. static const char pattern[] = "12345";
  9. static char *temp_file;
  10. static void
  11. do_prepare (void)
  12. {
  13. int fd = create_temp_file ("bug-ungetc.", &temp_file);
  14. if (fd == -1)
  15. {
  16. printf ("cannot create temporary file: %m\n");
  17. exit (1);
  18. }
  19. write (fd, pattern, sizeof (pattern));
  20. close (fd);
  21. }
  22. static int
  23. do_one_test (int mode)
  24. {
  25. FILE *f;
  26. f = fopen (temp_file, "r");
  27. if (f == NULL)
  28. {
  29. printf ("could not open temporary file: %m\n");
  30. return 1;
  31. }
  32. if (mode == 1 && ftell (f) != 0)
  33. {
  34. printf ("first ftell returned wrong position %ld\n", ftell (f));
  35. return 1;
  36. }
  37. if (fgetc (f) != '1' || fgetc (f) != '2')
  38. {
  39. puts ("fgetc failed");
  40. return 1;
  41. }
  42. if (mode == 2 && ftell (f) != 2)
  43. {
  44. printf ("second ftell returned wrong position %ld\n", ftell (f));
  45. return 1;
  46. }
  47. if (ungetc ('6', f) != '6')
  48. {
  49. puts ("ungetc failed");
  50. return 1;
  51. }
  52. if (ftell (f) != 1)
  53. {
  54. printf ("third ftell returned wrong position %ld\n", ftell (f));
  55. return 1;
  56. }
  57. if (fgetc (f) != '6')
  58. {
  59. puts ("fgetc failed");
  60. return 1;
  61. }
  62. if (ftell (f) != 2)
  63. {
  64. printf ("fourth ftell returned wrong position %ld\n", ftell (f));
  65. return 1;
  66. }
  67. fclose (f);
  68. return 0;
  69. }
  70. static int
  71. do_test (void)
  72. {
  73. int mode;
  74. for (mode = 0; mode <= 2; mode++)
  75. if (do_one_test (mode))
  76. return 1;
  77. return 0;
  78. }