C fflush() Function Tutorial

In this section, we will learn what the fflush() function is and how it works in C.

C fflush() Function

By default, when we want to send content to a file, that content is first stored in a portion of the memory called buffer and then when that buffer is filled, those contents will be sent to the hard-disk where the actual file is stored.

But we can send the content stored in this buffer before it gets filled via the call to the `fflush()` function.

Note: the prototype exists in the `stdio.h` header file and so we need to include the file in order to work with the function.

C fflush() Function Syntax:

Here’s the prototype of the function:

int fflush(FILE *stream)

C fflush() Function Parameters

This function takes only one argument and that is the address of the memory location allocated to the FILE-structure of the target file.

C fflush() Function Return Value

The returned value of the function is 0 in case of a successful operation and EOF in case there was an error.

Example: using fflush() function in C

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

int main() {

    //Call the the fopen function in order to open the file in read-write mode.
    FILE *file = fopen("G:/fileOne.txt","a+");
    //if there was a problem on opening the file, exit the program.
    if (file == NULL){
        printf("Could not open the file");
        exit(EXIT_FAILURE);

    }

    char * string = "This is how you use the fflush() function";

    for (int i = 0 ; i< strlen(string);i++){
        putc(*(string+i),file);
        fflush(file);
    }

    fclose(file);

    printf("\nDone\n");
    return 0;
}

Output:

Done

Note: in this example, after each call to `putc()` function, we then called `fflush()` function to send that element from the buffer to the hard-disk.

Also remember that calling the `fflush()` many times in a program can slow down the speed of writing content to a file because of constant communication between the memory and the hard-disk (This hard-disk is slow compared to the memory and which will slow down our program as well).

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies