How to use ffllush(stdout) in c?

3.8k Views Asked by At

I know about fflush(stdin) that it is undefined behavior according to standard. But when it comes to stdout, there is no such restriction. I did google to get the concept of using stdout as a parameter of fflush, but I couldn't get it.

Can someone elaborate the fflush function having stdout as a parameter with an easy example?

1

There are 1 best solutions below

3
On

When printing (e.g. printf), the output is put into a buffer and may not be written to the console until a newline character is displayed. To ensure that everything in the buffer is written to the console, fflush(stdout) may be used.

One example is displaying the progress of some process:

   for(int i = 0; i < 100; i++)
   {
       <...calculation...>
       printf("."); // Print a dot after each iteration to show progress
       fflush(stdout);   // The dot may be buffered. This ensures that it is displayed immediately
   }