Should fflush()
not be used to flush a buffer even if it is an output stream?
What is it useful for? How do we flush a buffer in general?
Should fflush()
not be used to flush a buffer even if it is an output stream?
What is it useful for? How do we flush a buffer in general?
Flushing the output buffers:
printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is
or
fprintf(fd, "Buffered, will be flushed");
fflush(fd); //Prints to a file
Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf()
it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf
something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.
Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf()
, so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.
I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf()
is an expensive operation (which is why it doesn't by default flush the buffer).
As far as flushing the input buffer (stdin
), you should not do that. Flushing stdin
is undefined behavior according to the C11 standard §7.21.5.2 part 2:
If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.
On some systems, Linux being one as you can see in the man page for fflush()
, there's a defined behavior but it's system dependent so your code will not be portable.
Now if you're worried about garbage "stuck" in the input buffer you can use fpurge()
on that.
See here for more on fflush()
and fpurge()
fflush(stdout)
won't have any effect on stdin
, so you won't lose any input. fpurge
isn't mentioned in any standard as far as I can find. –
Bernita fprintf(stderr, "got here!\n");
. Since stderr
is not buffered, it will be printed immediately. –
Condensation © 2022 - 2024 — McMap. All rights reserved.
fflush()
is for. – Grosz