0
0
C++programming~5 mins

File open and close operations in C++

Choose your learning style9 modes available
Introduction

We open files to read or write data. Closing files saves changes and frees resources.

Saving user data to a file after input
Reading configuration settings from a file
Logging program actions to a file
Loading a list of items from a file
Syntax
C++
#include <fstream>

std::ifstream inputFile;
inputFile.open("filename.txt");

// use the file

inputFile.close();

Use std::ifstream to open files for reading.

Always close files after finishing to avoid errors.

Examples
Open a file to write data using std::ofstream.
C++
#include <fstream>

std::ofstream outputFile;
outputFile.open("output.txt");
// write data
outputFile.close();
Open a file for reading by passing the filename to the constructor.
C++
#include <fstream>

std::ifstream inputFile("input.txt");
// read data
inputFile.close();
Open a file for both reading and writing using std::fstream.
C++
#include <fstream>

std::fstream file;
file.open("data.txt", std::ios::in | std::ios::out);
// read and write
file.close();
Sample Program

This program opens a file named example.txt for writing, writes a line, then closes the file. It prints a success message.

C++
#include <iostream>
#include <fstream>

int main() {
    std::ofstream file;
    file.open("example.txt");
    if (!file.is_open()) {
        std::cout << "Failed to open file." << std::endl;
        return 1;
    }
    file << "Hello, file!\n";
    file.close();
    std::cout << "File written and closed successfully." << std::endl;
    return 0;
}
OutputSuccess
Important Notes

Always check if the file opened successfully before using it.

Closing a file flushes any data still in memory to the disk.

Summary

Open files to read or write data.

Use open() to start using a file and close() when done.

Check if the file opened successfully to avoid errors.