bug-ungetc.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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_test (void)
  25. {
  26. int i;
  27. FILE *f;
  28. char buf[10];
  29. long offset, diff;
  30. int result = 0;
  31. f = fopen (temp_file, "rw");
  32. rewind (f);
  33. for (i = 0; i < 3; i++)
  34. printf ("%c\n", getc (f));
  35. offset = ftell (f);
  36. printf ("offset = %ld\n", offset);
  37. if (ungetc ('4', f) != '4')
  38. {
  39. printf ("ungetc failed\n");
  40. abort ();
  41. }
  42. printf ("offset after ungetc = %ld\n", ftell (f));
  43. i = fread ((void *) buf, 4, (size_t) 1, f);
  44. printf ("read %d (%c), offset = %ld\n", i, buf[0], ftell (f));
  45. diff = ftell (f) - offset;
  46. if (diff != 3)
  47. {
  48. printf ("ftell did not update properly. got %ld, expected 3\n", diff);
  49. result = 1;
  50. }
  51. fclose (f);
  52. return result;
  53. }