Open In App

fclose() Function in C

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C language, fclose() is a standard library function used to close a file that was previously opened using fopen(). This function is the itegral part of the file handling in C which allows the users to free the memory occupied by the file once all the operations are done on it.

In this article, we will learn about the fclose() function, its syntax and how it behaves in different scenarios.

Syntax of fclose()

The syntax of fclose is straigforward:

fclose(file_pointer);

Parameters

  • file_pointer: A pointer to a FILE object that identifies the stream to be closed.

Return Value

This function only returns two values:

  • 0: When the file is successfully closed.
  • EOF: When an error occurred while closing the file.

Example of fclose() in C

C
// C program to demonstrate the use of fclose()
#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.

Related Articles:


Next Article

Similar Reads