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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Flushing the output buffers:
or
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 toprintfsomething 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. Flushingstdinis undefined behavior according to the C11 standard §7.21.5.2 part 2: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()andfpurge()