fclose() Function in C

Last Updated : 22 Jul, 2026

The fclose() function is a standard library function declared in the <stdio.h> header file. It is used to close a file that was previously opened using fopen() or related file-opening functions.

  • It releases the resources associated with the file and ensures that any buffered data is written to the file.
  • It should always be called after completing file operations to prevent resource leaks.
  • On success, it returns 0; on failure, it returns EOF.
C
#include <stdio.h>

int main()
{
    // Open the file for writing
    FILE *file_ptr = fopen("example.txt", "w");
    if (file_ptr == NULL)
    {
        perror("Error opening file");
        return 1;
    }

    // Write some data to the file
    fprintf(file_ptr, "Hello, World!\n");

    // Close the file and check for errors
    if (fclose(file_ptr) != 0)
    {
        perror("Error closing file");
        return 1;
    }

    printf("File operations completed successfully.\n");
    return 0;
}

Output
File operations completed successfully.

Note: Using the file stream after it has been closed with fclose() results in undefined behavior. This means that any operations on the closed file stream can lead to unpredictable results, including crashes or data corruption.

Syntax

int fclose(FILE *stream);

Parameters

  • stream: Pointer to the file that needs to be closed.

Return Value

  • Returns 0 if the file is closed successfully.
  • Returns EOF if an error occurs while closing the file.

Working

The fclose() function closes an opened file and releases the resources associated with it.

  • Open a file using fopen() or another file-opening function.
  • Perform the required read or write operations on the file.
  • Call fclose() by passing the file pointer as an argument.
  • The function flushes any buffered data, closes the file, and releases the allocated resources.

Advantages

The fclose() function helps manage files safely and efficiently.

  • Ensures that all buffered data is written to the file before closing.
  • Releases the memory and system resources associated with the file.
  • Prevents resource leaks by properly terminating file operations.

Limitations

Although fclose() is essential for file handling, it has a few limitations.

  • It can only close files that have been successfully opened.
  • Once a file is closed, the associated file pointer becomes invalid and cannot be used unless the file is reopened.
  • Calling fclose() on an invalid or already closed file pointer results in undefined behavior.
Comment