bug-ungetc.c 1.2 KB

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