RE: [PATCH v2] fixdep: use fflush() and ferror() to ensure successful write to files

From: David Laight
Date: Tue Mar 01 2022 - 04:48:38 EST


From: Masahiro Yamada
> Sent: 01 March 2022 09:06
>
> On Tue, Mar 1, 2022 at 11:28 AM David Laight <David.Laight@xxxxxxxxxx> wrote:
> >
> > The return value from fprintf() is normally the number of bytes written to
> > the internal buffer (8k in glibc?)
> >
> > Only if the buffer is full and an actual write() is done do you get any indication of an error.
> >
> > So you can use the error return from fprintf() to terminate a loop – but it usually
> > just isn’t worth the effort.
> >
> > The error status returned by ferror() is ‘sticky’, so you need only check once.
> >
> > But you need to check before fclose().
> >
> > Since fclose() has to write out the buffer – that write can also fail.
> >
> > I’m not sure whether fclose() returns and error in that case, but adding fflush()
> > makes the coding easier.
>
>
> I just checked this.
>
> fclose() returns -1 if it fails to flush the buffer.

But you still need to check ferror() before it.
So you might as well do fflush(); if (ferror()); fclose();

Then there is only one error exit path.

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
Registration No: 1397386 (Wales)