aboutsummaryrefslogtreecommitdiff
path: root/libio/bug-fseek.c
blob: 1b60580b53cef07a9de7c735133e4cb207fdcb1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


static char *fname;


static void do_prepare (void);
#define PREPARE(argc, argv) do_prepare ()
static int do_test (void);
#define TEST_FUNCTION do_test ()
#include <test-skeleton.c>


static void
do_prepare (void)
{
  static const char pattern[] = "12345678901234567890";
  int fd = create_temp_file ("bug-fseek.", &fname);
  if (fd == -1)
    {
      printf ("cannot create temporary file: %m\n");
      exit (1);
    }

  if (write (fd, pattern, sizeof (pattern)) != sizeof (pattern))
    {
      perror ("short write");
      abort ();
    }
  close (fd);
}



static int
do_test (void)
{
  FILE *f;
  int result = 0;
  char buf[10];


  if ((f = fopen (fname, "r")) == (FILE *) NULL)
    {
      perror ("fopen(\"r\")");
    }

  fread (buf, 3, 1, f);
  errno = 0;
  if (fseek (f, -10, SEEK_CUR) == 0)
    {
      printf ("fseek() for r to before start of file worked!\n");
      result = 1;
    }
  else if (errno != EINVAL)
    {
      printf ("\
fseek() for r to before start of file did not set errno to EINVAL.  \
Got %d instead\n",
	 errno);
      result = 1;
    }

  fclose (f);


  if ((f = fopen (fname, "r+")) == (FILE *) NULL)
    {
      perror ("fopen(\"r+\")");
    }

  fread (buf, 3, 1, f);
  errno = 0;
  if (fseek (f, -10, SEEK_CUR) == 0)
    {
      printf ("fseek() for r+ to before start of file worked!\n");
      result = 1;
    }
  else if (errno != EINVAL)
    {
      printf ("\
fseek() for r+ to before start of file did not set errno to EINVAL.  \
Got %d instead\n",
	 errno);
      result = 1;
    }

  fclose (f);


  if ((f = fopen (fname, "r+")) == (FILE *) NULL)
    {
      perror ("fopen(\"r+\")");
    }

  fread (buf, 3, 1, f);
  if (ftell (f) != 3)
    {
      puts ("ftell failed");
      return 1;
    }
  errno = 0;
  if (fseek (f, -10, SEEK_CUR) == 0)
    {
      printf ("fseek() for r+ to before start of file worked!\n");
      result = 1;
    }
  else if (errno != EINVAL)
    {
      printf ("\
fseek() for r+ to before start of file did not set errno to EINVAL.  \
Got %d instead\n",
	 errno);
      result = 1;
    }

  fclose (f);

  return result;
}