bug-ungetc3.c 1.7 KB

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