1 /* Test for ungetc bugs.  */
2 
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 
7 #undef assert
8 #define assert(x) \
9   if (!(x)) \
10     { \
11       fputs ("test failed: " #x "\n", stderr); \
12       retval = 1; \
13       goto the_end; \
14     }
15 
16 int
main(int argc,char * argv[])17 main (int argc, char *argv[])
18 {
19   char name[] = "/tmp/tst-ungetc.XXXXXX";
20   FILE *fp = NULL;
21   int retval = 0;
22   int c;
23   char buffer[64];
24 
25   int fd = mkstemp (name);
26   if (fd == -1)
27     {
28       printf ("mkstemp failed: %m\n");
29       return 1;
30     }
31   close (fd);
32   fp = fopen (name, "w");
33   assert (fp != NULL)
34   fputs ("bla", fp);
35   fclose (fp);
36   fp = NULL;
37 
38   fp = fopen (name, "r");
39   assert (fp != NULL);
40   assert (ungetc ('z', fp) == 'z');
41   assert (getc (fp) == 'z');
42   assert (getc (fp) == 'b');
43   assert (getc (fp) == 'l');
44   assert (ungetc ('m', fp) == 'm');
45   assert (getc (fp) == 'm');
46   assert ((c = getc (fp)) == 'a');
47   assert (getc (fp) == EOF);
48   assert (ungetc (c, fp) == c);
49   assert (feof (fp) == 0);
50   assert (getc (fp) == c);
51   assert (getc (fp) == EOF);
52   fclose (fp);
53   fp = NULL;
54 
55   fp = fopen (name, "r");
56   assert (fp != NULL);
57   assert (getc (fp) == 'b');
58   assert (getc (fp) == 'l');
59   assert (ungetc ('b', fp) == 'b');
60   assert (fread (buffer, 1, 64, fp) == 2);
61   assert (buffer[0] == 'b');
62   assert (buffer[1] == 'a');
63 
64 the_end:
65   if (fp != NULL)
66     fclose (fp);
67   unlink (name);
68 
69   return retval;
70 }
71