fclose() in C - Source Code Example

In this source code example, we will see how to use the fclose() function in C programming with an example.

fclose() Function Overview

fclose() is used to close a file in C. After working with a file, it's a good idea to close it. This makes sure everything is saved and frees up resources.

Source Code Example

#include <stdio.h>

int main() {
    // Opening a file to write something
    FILE *filePtr = fopen("example.txt", "w");
    if (filePtr == NULL) {
        printf("Oops! Couldn't open the file.\n");
        return 1;

    // Writing a simple message to the file
    fprintf(filePtr, "Hi Ram! This is an example in C.\n");

    // Now, let's close the file using fclose
    printf("File closed successfully!\n");

    return 0;


File closed successfully!


What we did here:

1. We first opened a file named "example.txt" for writing.

2. We wrote a greeting message in it.

3. Then, we used fclose() to close the file.

4. We printed a message to say the file was closed.

Closing files is important. It makes sure our changes are saved and helps avoid any problems.