C fflush()

The fflush() function defined in the stdio.h header file. It helps to update the stream that means it flushes the contents of any output stream to the corresponding file.


int fflush(FILE *stream); #where stream should be a file pointer

 

fflush() Parameters: 

The fflush() function takes a single parameter.

Parameter Description Required / Optional
stream the pointer to a FILE object that specifies a buffered stream Required

fflush() Return Value

The return value of fflush() function is zero in success and EOF in case of error case also sets the error indicator.

Input Return Value
If success zero
if error EOF

Examples of fflush() 

Example 1: Working of fflush() function in C?


#include <stdio.h>

int main()
{
   char chr[50];
   FILE *pnt;
   pnt = fopen("mytestfile.txt", "r+");
   if (pnt)
   {
      fputs("Library function examples", pnt);
      fflush(chr); // flushes the buffer 
      fgets(chr, 20, pnt); 
      puts(chr); // It displays buffer data in output
      fclose(pnt);
      return 0;
   }
   return 1;
}

Output:


Library function examples

Example 2: How fflush() works in C?


#include <stdio.h>
#include <stdlib.h>
int main()
{
          char chr[20];
          int i;
          for (i = 0; i<4; i++)
          {
                   scanf("%[^\n]s", chr);
                   printf("%s\n", chr);
                   // used to clear the buffer
                   // and accept the next string
                   fflush(stdin);
          }
          return 0;
}

Output:

C Programming
C Programming
C Programming
C Programming