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

source code of glibc/libio/bug-ungetc3.c