Make fflush after ungetc work on BSD platforms.
[gnulib.git] / lib / fflush.c
1 /* fflush.c -- allow flushing input streams
2    Copyright (C) 2007-2008 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Eric Blake. */
18
19 #include <config.h>
20
21 /* Specification.  */
22 #include <stdio.h>
23
24 #include <errno.h>
25 #include <unistd.h>
26
27 #include "freading.h"
28 #include "fpurge.h"
29
30 #undef fflush
31
32 /* Flush all pending data on STREAM according to POSIX rules.  Both
33    output and seekable input streams are supported.  */
34 int
35 rpl_fflush (FILE *stream)
36 {
37   int result;
38   off_t pos;
39
40   /* When stream is NULL, POSIX and C99 only require flushing of "output
41      streams and update streams in which the most recent operation was not
42      input", and all implementations do this.
43
44      When stream is "an output stream or an update stream in which the most
45      recent operation was not input", POSIX and C99 requires that fflush
46      writes out any buffered data, and all implementations do this.
47
48      When stream is, however, an input stream or an update stream in
49      which the most recent operation was input, C99 specifies nothing,
50      and POSIX only specifies behavior if the stream is seekable.
51      mingw, in particular, drops the input buffer, leaving the file
52      descriptor positioned at the end of the input buffer. I.e. ftell
53      (stream) is lost.  We don't want to call the implementation's
54      fflush in this case.
55
56      We test ! freading (stream) here, rather than fwriting (stream), because
57      what we need to know is whether the stream holds a "read buffer", and on
58      mingw this is indicated by _IOREAD, regardless of _IOWRT.  */
59   if (stream == NULL || ! freading (stream))
60     return fflush (stream);
61
62   /* Clear the ungetc buffer.
63
64      This is needed before fetching the file-position indicator, because
65      1) The file position indicator is incremented by fgetc() and decremented
66         by ungetc():
67         <http://www.opengroup.org/susv3/functions/fgetc.html>
68           "The file-position indicator is decremented by each successful
69            call to ungetc()..."
70         <http://www.opengroup.org/susv3/functions/ungetc.html>
71           "... the fgetc() function shall ... advance the associated file
72         position indicator for the stream ..."
73      2) <http://www.opengroup.org/susv3/functions/ungetc.html> says:
74           "The value of the file-position indicator for the stream after
75            reading or discarding all pushed-back bytes shall be the same
76            as it was before the bytes were pushed back."
77      3) Here we are discarding all pushed-back bytes.
78
79      Unfortunately it is impossible to implement this on platforms with
80      _IOERR, because an ungetc() on this platform prepends the pushed-back
81      bytes to the buffer without an indication of the limit between the
82      pushed-back bytes and the read-ahead bytes.  */
83 #if defined __sferror               /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */
84   {
85 # if defined __NetBSD__ || defined __OpenBSD__
86     struct __sfileext
87       {
88         struct  __sbuf _ub; /* ungetc buffer */
89         /* More fields, not relevant here.  */
90       };
91     if (((struct __sfileext *) stream->_ext._base)->_ub._base != NULL)
92 # else
93     if (stream->_ub._base != NULL)
94 # endif
95       {
96         stream->_p += stream->_r;
97         stream->_r = 0;
98       }
99   }
100 #endif
101
102   /* POSIX does not specify fflush behavior for non-seekable input
103      streams.  Some implementations purge unread data, some return
104      EBADF, some do nothing.  */
105   pos = ftello (stream);
106   if (pos == -1)
107     {
108       errno = EBADF;
109       return EOF;
110     }
111
112   /* To get here, we must be flushing a seekable input stream, so the
113      semantics of fpurge are now appropriate to clear the buffer.  To
114      avoid losing data, the lseek is also necessary.  */
115   result = fpurge (stream);
116   if (result != 0)
117     return result;
118
119 #if defined __sferror && defined __SNPT /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */
120
121   {
122     /* Disable seek optimization for the next fseeko call.  This tells the
123        following fseeko call to seek to the desired position directly, rather
124        than to seek to a block-aligned boundary.  */
125     int saved_flags = stream->_flags & (__SOPT | __SNPT);
126     stream->_flags = (stream->_flags & ~__SOPT) | __SNPT;
127
128     result = fseeko (stream, pos, SEEK_SET);
129
130     stream->_flags = (stream->_flags & ~(__SOPT | __SNPT)) | saved_flags;
131   }
132   return result;
133
134 #else
135
136   pos = lseek (fileno (stream), pos, SEEK_SET);
137   if (pos == -1)
138     return EOF;
139   /* After a successful lseek, update the file descriptor's position cache
140      in the stream.  */
141 # if defined __sferror           /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */
142   stream->_offset = pos;
143   stream->_flags |= __SOFF;
144 # endif
145
146   return 0;
147
148 #endif
149 }