fclose() function in C++

In this guide, you will learn what is fclose() function is in C++ programming and how to use it with an example.

1. fclose() Function Overview

The fclose() function is a part of the <cstdio> library in C++. It is used to close a file stream that was previously opened using functions like fopen(). It releases the resources associated with the file stream and ensures that any buffered data is written to the file.

Signature:

int fclose(FILE* stream);

Parameters:

- stream: A pointer to the file stream that needs to be closed.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    // Open a file for writing
    FILE *file = fopen("sample.txt", "w");

    if (file) {
        std::cout << "File opened successfully for writing." << std::endl;

        // Writing data to the file
        fprintf(file, "Hello, World!");

        // Close the file
        if (fclose(file) == 0) {
            std::cout << "File closed successfully." << std::endl;
        } else {
            std::cout << "Error in closing the file." << std::endl;
        }
    } else {
        std::cout << "Error in opening the file." << std::endl;
    }

    return 0;
}

Output:

File opened successfully for writing.
File closed successfully.

3. Explanation

1. We've included the <iostream> header for standard input/output operations and <cstdio> for the fopen(), fclose(), and fprintf() functions.

2. We open a file named "sample.txt" for writing. If the file does not exist, it will be created. If it already exists, its contents will be truncated.

3. We then write the "Hello, World!" string to the file using the fprintf() function.

4. Finally, we close the file using the fclose() function and check if the file was closed successfully.


Comments