C fclose() Function | Close an Open File

Introduction

The fclose() function in C is a standard library function that closes an open file associated with a stream. It is part of the C standard library (stdio.h) and is used to ensure that all data is properly written to the file and resources are freed.

fclose() Function Syntax

The syntax for the fclose() function is as follows:

int fclose(FILE *stream);

Parameters:

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

Returns:

  • The function returns 0 if the file was closed successfully. If an error occurs, EOF is returned.

Understanding fclose()

The fclose() function closes the file associated with the given FILE pointer. It ensures that any buffered output is flushed to the file and that resources allocated for the file are properly released. Failing to close files can lead to memory leaks and data corruption.

Examples

Closing a File after Reading

To demonstrate how to use fclose() to close a file after reading, we will write a simple program.

Example

#include <stdio.h>

int main() {
    FILE *file;

    // Open the file for reading
    file = fopen("example.txt", "r");

    // Check if the file was opened successfully
    if (file == NULL) {
        printf("Error: Could not open file for reading.\n");
        return 1;
    }

    // Perform file reading operations here

    // Close the file
    if (fclose(file) != 0) {
        printf("Error: Could not close the file.\n");
        return 1;
    }

    return 0;
}

Closing a File after Writing

This example shows how to use fclose() to close a file after writing.

Example

#include <stdio.h>

int main() {
    FILE *file;

    // Open the file for writing
    file = fopen("example.txt", "w");

    // Check if the file was opened successfully
    if (file == NULL) {
        printf("Error: Could not open file for writing.\n");
        return 1;
    }

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

    // Close the file
    if (fclose(file) != 0) {
        printf("Error: Could not close the file.\n");
        return 1;
    }

    return 0;
}

Handling File Closure in Error Scenarios

This example demonstrates how to handle file closure properly in error scenarios.

Example

#include <stdio.h>

int main() {
    FILE *file;

    // Open the file for reading
    file = fopen("example.txt", "r");

    // Check if the file was opened successfully
    if (file == NULL) {
        printf("Error: Could not open file for reading.\n");
        return 1;
    }

    // Perform file reading operations here
    // Simulating an error during file operations
    int error_occurred = 1;

    // Close the file
    if (fclose(file) != 0) {
        printf("Error: Could not close the file.\n");
        return 1;
    }

    if (error_occurred) {
        printf("Error: An error occurred during file operations.\n");
        return 1;
    }

    return 0;
}

Real-World Use Case

Logging Application with Proper Resource Management

In real-world applications, ensuring that files are properly closed is critical for resource management and data integrity.

Example

#include <stdio.h>
#include <time.h>

void log_message(const char *message) {
    FILE *logfile = fopen("log.txt", "a");
    if (logfile == NULL) {
        printf("Error: Could not open log file.\n");
        return;
    }

    time_t now = time(NULL);
    fprintf(logfile, "%s: %s\n", ctime(&now), message);

    if (fclose(logfile) != 0) {
        printf("Error: Could not close log file.\n");
    }
}

int main() {
    log_message("Application started.");
    log_message("An event occurred.");

    return 0;
}

Output (in "log.txt"):

Wed Jul  4 12:34:56 2023: Application started.
Wed Jul  4 12:34:57 2023: An event occurred.

Conclusion

The fclose() function in C closes a file that was previously opened using functions like fopen(). It takes the file pointer as an argument and returns 0 on success or EOF on failure, ensuring that resources associated with the file are released and changes are saved.

Comments