* lib/stdio_.h [REPLACE_FFLUSH]: Declare rpl_fflush.
[gnulib.git] / tests / test-fflush.c
1 /* Test of POSIX compatible fflush() function.
2    Copyright (C) 2007 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* Written by Eric Blake, 2007.  */
19
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include <stdio.h>
25 #include <unistd.h>
26
27 int
28 main (int argc, char *argv[])
29 {
30   FILE *f;
31   char buffer[10];
32   int fd;
33
34   /* Create test file.  */
35   f = fopen ("test-fflush.txt", "w");
36   if (!f || fwrite ("1234567890", 1, 10, f) != 10 || fclose (f) != 0)
37     {
38       fputs ("Failed to create sample file.\n", stderr);
39       unlink ("test-fflush.txt");
40       return 1;
41     }
42
43   /* Test fflush.  */
44   f = fopen ("test-fflush.txt", "r");
45   fd = fileno (f);
46   if (!f || 0 > fd || fread (buffer, 1, 5, f) != 5)
47     {
48       fputs ("Failed initial read of sample file.\n", stderr);
49       fclose (f);
50       unlink ("test-fflush.txt");
51       return 1;
52     }
53   /* For deterministic results, ensure f read a bigger buffer.  */
54   if (lseek (fd, 0, SEEK_CUR) == 5)
55     {
56       fputs ("Sample file was not buffered.\n", stderr);
57       fclose (f);
58       unlink ("test-fflush.txt");
59       return 1;
60     }
61   /* POSIX requires fflush-fseek to set file offset of fd.  */
62   if (fflush (f) != 0 || fseek (f, 0, SEEK_CUR) != 0)
63     {
64       fputs ("Failed to flush sample file.\n", stderr);
65       fclose (f);
66       unlink ("test-fflush.txt");
67       return 1;
68     }
69   /* Check that offset is correct.  */
70   if (lseek (fd, 0, SEEK_CUR) != 5)
71     {
72       fputs ("File offset is wrong.\n", stderr);
73       fclose (f);
74       unlink ("test-fflush.txt");
75       return 1;
76     }
77   /* Check that file reading resumes at correct location.  */
78   if (fgetc (f) != '6')
79     {
80       fputs ("Failed to read next byte of file.\n", stderr);
81       fclose (f);
82       unlink ("test-fflush.txt");
83       return 1;
84     }
85   fclose (f);
86   unlink ("test-fflush.txt");
87   return 0;
88 }