fflush() function in C language with Example

Here, we are going to learn about the fflush() function of library header stdio.h in C language with its syntax, example.
Submitted by Souvik Saha, on January 06, 2019

fflush() function in C


    int fflush(FILE *filename);


    FILE *filename

Return type: 0 or EOF

Use of function:

When we are dealing with file handling, instead of handling the files we handle the streams. There are three types of streams stdin (standard input), stderr (standard error), stdout (standard output). fflush() function is used to flush the buffer after each iteration in the program. When we open a file for the write operation, a call to fflush() function helps to write on the file and also it clears the buffer from the stream. The prototype of the ffiush() function is: int fflush(FILE* filename);

A return value zero indicates that it is successful and a return value EOF implies that there is some error occurred.

fflush() example in C

#include <stdio.h>
#include <stdlib.h>

int main()
    //Initialize the file pointer
    FILE* f;
    //Take a array of characters
    char ch[100];
    //Create the file for write operation
    f = fopen("includehelp.txt", "w");
    printf("Enter five strings\n");
    for (int i = 0; i < 4; i++) {
        //take the strings from the users
        scanf("%[^\n]", &ch);
        //write back to the file
        fputs(ch, f);
        //every time take a new line for the new entry string
        fputs("\n", f);
        //except for last entry.Otherwise print the last line twice
        //clear the stdin stream buffer
        //if we don't write this then after taking string
        //%[^\n] is waiting for the '\n' or white space

    //take the strings from the users
    scanf("%[^\n]", &ch);
    fputs(ch, f);
    //close the file after write operation is over

    //open a file
    f = fopen("includehelp.txt", "r");
    printf("File content is--\n");
    printf("\n...............print the strings..............\n");
    while (!feof(f)) {
        //takes the first 100 character in the character array
        fgets(ch, 100, f);
        //and print the strings
        printf("%s", ch);

    //close the file

    return 0;


fflush example in c 1

If we don't use the fflush() function here. Then the output will be...

fflush example in c 2

C stdio.h Library Functions Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.