well...i tried in google...but actually i didn't quite get it. :)
http://www.thinkage.ca/english/gcos/expl/c/lib/fflush.html
in the above link they are saying, user should definitely NOT write code of the form

printf("Prompt: ");
fflush(stdout);
gets(s);

but before we used fflush after printf...for example here jephthah gave a solution where he used fflush after printf and mentioned // printf did not have newline, need to flush When and why we need to use fflush exactly?
thanks to all..

Recommended Answers

All 8 Replies

When you write to 'buffered' device, sometimes the system will hold the characters in the buffer until a specific thing happens:
1) the buffer is filled
2) a NEWLINE \n is added
3) an explicit command (flush) is used
It all depends on how the compiler I/O is designed.
So on some compilers, a printf() or cout command may not work immediately. Therefore, you flush the buffer when you need the output right away.

>>When and why we need to use fflush exactly?
Depends on the operating system. When writing to the screen (MS-Windows) I never use fflush() because MS-Windows seems to write immediately. I have seen the problem on *nix computers where it was necessary even after putting '\n' in the output stream.

When to do it? You won't have to put it after every printf() statement, you can delay callinf fflush() until after all printf() statements but before any input statements. Lets say you want to display a menu that has 10 printf() statements. Just put the fflush() after the last printf().

For disk file streams call fflush() after all writing has been done. Its not necessary to call fflush() before the file is closed because fclose() will do that anyway.

>in the above link they are saying, user should definitely NOT write code of the form
They're wrong. That code (ignoring gets) is best practice. Assuming for a moment that the author of that page isn't an idiot, I'd say there's an implicit assumption about the system/implementation here:

let the implicit output-flushing routines handle everything for you

There are two implicit flushing "routines":

  1. When a newline character is sent to the output stream in question.
  2. When the output stream buffer is full.

It should be obvious that #2 can't be relied on if you want your user prompts to show up...well, promptly. If you want user input to be on the same line as the prompt a newline at the end of the prompt to force a flush isn't practical. The only other way to flush the stream is fflush.

The truly humorous part is how the biggest argument against fflush from that page is overhead. Let's think about this logically using the two examples:

/* Example 1 */
printf("Prompt: ");
fflush(stdout);
gets(s);
/* Example 2 */
printf("Prompt: ");
gets(s);

Assuming the "implicit flushing routines" handle everything for you, one would expect both prompts to show up before gets blocks for input. This is the normal expected behavior, and if the second example fails to do it (because there's no flush), that's a strong argument in favor of using fflush.

However, if both examples do show the prompt correctly, that means under the hood a flush is being signaled whether you call fflush or not. It's not unreasonable for an stdio implementation to tie input and output streams together for this kind of convenience.

Now for the contradiction. That page says fflush has significant overhead, but only if there's output in the buffer waiting to be flushed. If you don't call fflush and the implementation does it automatically anyway, the overhead is still there. If you do call fflush, the overhead moves to your call and the automatic call no longer has "significant overhead" because the output buffer is now empty.

So in both examples, assuming an automatic flush, the overhead is present, and when calling fflush explicitly the overhead isn't increased by more than perhaps a no-op function call. I'm sensing faulty logic here. Of course, an automatic flush isn't guaranteed, so not using fflush is non-portable.

It gets better too:

Since the flush operation takes place between the "printf" and the "gets", any input received after the prompt but before the "gets" is simply discarded.

This is completely ridiculous. fflush operates on output streams, and flushing an output stream doesn't affect even a tied input stream. I can't even fathom what the author was thinking when he wrote this. Perhaps if we were talking about flushing an input stream in a multithreaded application with a naive implementation of stdio that didn't set appropriate locks...

>When and why we need to use fflush exactly?
Use fflush when you haven't printed a newline and need the output to be written immediately.

commented: her answer resolved all my queries, even those i didn't ask!! :) +0

in the ... link they are saying, user should definitely NOT [use fflush(stdout) to clear the output buffer.]

that webpage is a joke. a bad joke. they actually instruct you to use gets() as an example of "safe code". this right there tells me they're talking out their ass.

for example here jephthah gave a solution where he used fflush after printf and mentioned // printf did not have newline, need to flush

if you don't print a newline, but want the line to display to the terminal, you should use fflush(stdout);. Your system may not need this, but some systems will not print text to the output buffer until a newline is found or the buffer is otherwise flushed.

Narue has explained it better than i can. i'm only commenting here because my name was dropped :icon_wink:

thanks waltP and dragon for explaining.
thanks narue, all the question was arising in my mind after waltp and dragon's replies were answered in your post. That explained all the things.

i'm only commenting here because my name was dropped :icon_wink:

well mate, if anyone is there whom i trust blindly, it's you(i trust some others too :icon_cheesygrin:). i like the way you criticize when someone does something wrong or doing something which is bad practice. i was just checking what i'm missing and what is the actual thing going on.
think i kinda got it.
thanks guys. rep+ to all ;)
sometimes it's feel good that i'm being trained by some of best programmers in the globe in this language.

if anyone is there whom i trust blindly, it's you

um, please don't do that... :P


trained by some of best programmers in the globe in this language

the sentiment is appreciated, but far from reality. Narue is probably the closest this forum has to a guru. the rest of are still in various stages of learning.

speaking only for myself, i'm still trying to master the basics.

the point is, be ready to question everything. websites, textbooks, and especially "experts"

.

But in this code:

printf("Filling array...\n"); //fflush(stdout);
fill_array(a, len, max);
printf("Array filled.\n");  //fflush(stdout);
print_sorted(array_sorted(a,len);

the first printf is delayed until the second one, even though there is a newline at the end. I am using the utility ts to measure times (e.g. ./my_sort 100000000 32768| ts), and I need every printf to be shown inmediately.
I am in Linux Ubuntu 10.10

Thanks.
Javier Ruiz

the first printf is delayed until the second one, even though there is a newline at the end.

Are you redirecting stdout to a file or other non-interactive device? This is getting into the nuances of the standard, but the rules state that stdout may be initialized to _IOFBF, or fully buffered, if and only if the stream is confirmed to be non-interactive. Otherwise it's either unbuffered or line buffered.

The intent of the rules is for interactive output to be written as soon as possible without sacrificing performance. Thus you'll find that pretty much every implementation initializes stdout as _IOLBF, or line buffered. In that case, the three rules of flushing apply:

  • If the buffer is full, it's flushed
  • If a newline is printed, the buffer is flushed
  • If fflush() is called, the buffer is flushed

This is the average case, but let's say you've redirected stdout to a file. Now it's no longer safe to assume that stdout is either line buffered or unbuffered, and the rules decrease to two:

  • If the buffer is full, it's flushed
  • If fflush() is called, the buffer is flushed

The only safe practice after redirection to a non-interactive stream is calling fflush() explicitly, or setting the buffer manually to either _IONBF or _IOLBF:

setvbuf(stdout, NULL, _IOLBF, BUFSIZ);

It may also be that for some reason even the interactive stream can't be confidently recognized as interactive, and your implementation is setting stdout to fully buffered. When in doubt, be explicit either by calling fflush() or set the buffer to what you want.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.