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