Messages in this thread | | | From | Masahiro Yamada <> | Date | Tue, 1 Mar 2022 18:06:04 +0900 | Subject | Re: [PATCH v2] fixdep: use fflush() and ferror() to ensure successful write to files |
| |
On Tue, Mar 1, 2022 at 11:28 AM David Laight <David.Laight@aculab.com> wrote: > > Someone send HTML mail – outlook is broken – only lets you top post :-( > > > > 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.
[ test code ] #include <stdio.h> int main(void) { char buf[2049]; int ret, i;
for (i = 0; i < 2048; i++) buf[i] = 'a';
buf[2048] = 0;
ret = printf("%s", buf); fprintf(stderr, "printf() returned: %d\n", ret);
ret = fclose(stdout); fprintf(stderr, "fclose() returned %d\n", ret);
return 0; }
I tested this on Debian buster.
I created a very small partition with 1K size, then write data to that partition.
root@buster:~# lsblk /dev/vdb1 NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT vdb1 254:17 0 1K 0 part root@buster:~# ./a.out > /dev/vdb1 printf() returned: 2048 fclose() returned -1
The buffer size seems 4k as far as I tested on Debian.
-- Best Regards Masahiro Yamada
| |