Make fflush rely on fpurge.
[gnulib.git] / lib / fflush.c
1 /* fflush.c -- allow flushing input streams
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. */
19
20 #include <config.h>
21 #include <errno.h>
22 #include <stdio.h>
23
24 #include "fpurge.h"
25
26 #undef fflush
27
28 /* Flush all pending data on STREAM according to POSIX rules.  Both
29    output and seekable input streams are supported.  */
30 int
31 rpl_fflush (FILE *stream)
32 {
33   int result;
34   off_t pos;
35
36   /* Try flushing the stream.  C89 guarantees behavior of output
37      streams, so we only need to worry if failure might have been on
38      an input stream.  When stream is NULL, POSIX only requires
39      flushing of output streams.  */
40   result = fflush (stream);
41   if (! stream || result == 0 || errno != EBADF)
42     return result;
43
44   /* POSIX does not specify fflush behavior for non-seekable input
45      streams.  */
46   pos = ftello (stream);
47   if (pos == -1)
48     {
49       errno = EBADF;
50       return EOF;
51     }
52
53   /* To get here, we must be flushing a seekable input stream, so the
54      semantics of fpurge are now appropriate to clear the buffer.  To
55      avoid losing data, the lseek is also necessary.  */
56   result = fpurge (stream);
57   if (result == 0 && lseek (fileno (stream), pos, SEEK_SET) == -1)
58     return EOF;
59   return result;
60 }