C fflush function forces to write buffer content to file

Syntax

C fflush function has the following format.

int fflush(FILE *stream);

C fflush function is from header file stdio.h.

Description

C fflush function forces the buffer contents to be written to the file.

It returns 0 on success or EOF on error.

Example

Force to write buffer content to file by using C fflush function.


#include <stdio.h>
#include <stdlib.h>
//from  w  w w  . j  a  v  a 2s  .c  o m
int main(void){
   FILE *fp;

   if((fp=fopen("test", "rb"))==NULL) {
      printf("Cannot open file.\n");
      exit(1);
   }

    char ch = 'C';
    int i;
    for(i=0; i<5; i++) {
      fwrite(ch, sizeof(ch), 1, fp);
      fflush(fp);
    }
    fclose(fp);
    return 0;
}

Flush the buffer


#include <stdio.h>
 /*from  w w  w  .  j  ava  2 s.c  o m*/
int main()
{
    char a,b;
 
    printf("Which character is greater?\n");
    printf("Type a single character:");
    a=getchar();
    fflush(stdin);
    printf("Type another character:");
    b=getchar();
    fflush(stdin);
 
    if(a > b)
    {
        printf("'%c' is greater than '%c'!\n",a,b);
    }
    else if (b > a)
    {
        printf("'%c' is greater than '%c'!\n",b,a);
    }
    else
    {
        printf("Next time, don't type the same character twice.");
    }
    return(0);
}

The code above generates the following result.





















Home »
  C Language »
    Function Reference »




assert.h
ctype.h
math.h
setjmp.h
signal.h
stdio.h
stdlib.h
string.h
time.h
wctype.h