1#include <errno.h>
2#include <stdio.h>
3#include <stdlib.h>
4#include <unistd.h>
5
6
7static char *fname;
8
9
10static void do_prepare (void);
11#define PREPARE(argc, argv) do_prepare ()
12static int do_test (void);
13#define TEST_FUNCTION do_test ()
14#include <test-skeleton.c>
15
16
17static void
18do_prepare (void)
19{
20 static const char pattern[] = "12345678901234567890";
21 int fd = create_temp_file (base: "bug-fseek.", filename: &fname);
22 if (fd == -1)
23 {
24 printf (format: "cannot create temporary file: %m\n");
25 exit (1);
26 }
27
28 if (write (fd, pattern, sizeof (pattern)) != sizeof (pattern))
29 {
30 perror ("short write");
31 abort ();
32 }
33 close (fd: fd);
34}
35
36
37
38static int
39do_test (void)
40{
41 FILE *f;
42 int result = 0;
43 char buf[10];
44
45
46 if ((f = fopen (fname, "r")) == (FILE *) NULL)
47 {
48 perror ("fopen(\"r\")");
49 }
50
51 fread (ptr: buf, size: 3, n: 1, stream: f);
52 errno = 0;
53 if (fseek (f, -10, SEEK_CUR) == 0)
54 {
55 printf (format: "fseek() for r to before start of file worked!\n");
56 result = 1;
57 }
58 else if (errno != EINVAL)
59 {
60 printf (format: "\
61fseek() for r to before start of file did not set errno to EINVAL. \
62Got %d instead\n",
63 errno);
64 result = 1;
65 }
66
67 fclose (f);
68
69
70 if ((f = fopen (fname, "r+")) == (FILE *) NULL)
71 {
72 perror ("fopen(\"r+\")");
73 }
74
75 fread (ptr: buf, size: 3, n: 1, stream: f);
76 errno = 0;
77 if (fseek (f, -10, SEEK_CUR) == 0)
78 {
79 printf (format: "fseek() for r+ to before start of file worked!\n");
80 result = 1;
81 }
82 else if (errno != EINVAL)
83 {
84 printf (format: "\
85fseek() for r+ to before start of file did not set errno to EINVAL. \
86Got %d instead\n",
87 errno);
88 result = 1;
89 }
90
91 fclose (f);
92
93
94 if ((f = fopen (fname, "r+")) == (FILE *) NULL)
95 {
96 perror ("fopen(\"r+\")");
97 }
98
99 fread (ptr: buf, size: 3, n: 1, stream: f);
100 if (ftell (stream: f) != 3)
101 {
102 puts (s: "ftell failed");
103 return 1;
104 }
105 errno = 0;
106 if (fseek (f, -10, SEEK_CUR) == 0)
107 {
108 printf (format: "fseek() for r+ to before start of file worked!\n");
109 result = 1;
110 }
111 else if (errno != EINVAL)
112 {
113 printf (format: "\
114fseek() for r+ to before start of file did not set errno to EINVAL. \
115Got %d instead\n",
116 errno);
117 result = 1;
118 }
119
120 fclose (f);
121
122 return result;
123}
124

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