C fclose() Function Tutorial

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

Close File in C: fclose() Function

As mentioned in the fopen() section, the first step in order to work with a file in C program is to open it!

This opening will cause a portion of the memory space to be allocated to the target file.

It is a good practice to release this allocated space after we’re done with the file in order to let other programs use the space if they needed.

This is where the `fclose()` function comes in.

Via this function, we can close and release the memory allocated to the FILE-structure of the target file.

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

C fclose() Function Syntax:

Here’s the prototype of the function:

int fclose(FILE *stream)

C fclose() Function Parameters

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

Note: we get this address when we open a file via the call to the `fopen()` function.

C fclose() Function Return Value

The returned value of the function is 0 on a successful operation and EOF otherwise.

Example: using fclose() 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 write mode.
    FILE *file = fopen("G:/fileOne.txt","w");
    //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 = "Hello,\nMy name is John Doe!\n";
    for (int i = 0 ; i<strlen(string);i++){
        fputc(*(string+i), file);
    }

    fclose(file);


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

Output:

Done
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies