Skip to content

Opening and Closing File

๐Ÿ“˜ File Handling in C++

File handling allows a C++ program to create, read, write, and manipulate files stored on the disk.

To perform file operations, C++ provides file stream classes from the <fstream> header:

Stream ClassPurpose
ifstreamInput file stream (read from file)
ofstreamOutput file stream (write to file)
fstreamInput and output stream (read & write)

๐Ÿ”‘ Opening a File in C++

To open a file, you create a stream object and use either:

  1. Constructor method
  2. open() function

โœ… 1. Using Constructor

ofstream outFile("data.txt");     // Opens file for writing
ifstream inFile("data.txt"); // Opens file for reading

โœ… 2. Using open() function

ofstream outFile;
outFile.open("data.txt"); // Opens file for writing

You can also specify file modes (more below).


โœ๏ธ Example: Writing to a File

#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream outFile("example.txt"); // Open for writing

if (outFile.is_open()) {
outFile << "Hello, file handling in C++!\n";
outFile << "Writing to a file.\n";
outFile.close(); // Always close the file
cout << "Data written successfully!" << endl;
} else {
cout << "File could not be opened." << endl;
}

return 0;
}

โœ๏ธ Example: Reading from a File

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
ifstream inFile("example.txt"); // Open for reading
string line;

if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close(); // Close the file
} else {
cout << "Unable to open file." << endl;
}

return 0;
}

๐Ÿ“Œ File Modes in C++

When opening a file, you can use file mode flags with open():

ModeDescription
ios::inOpen for reading
ios::outOpen for writing
ios::appAppend to end of file
ios::truncTruncate file if it exists
ios::binaryOpen in binary mode

๐Ÿงช Example:

fstream file;
file.open("data.txt", ios::in | ios::out); // Read & write

โœ… Closing a File

Always close a file after finishing operations using .close():

file.close();

Closing a file:

  • Saves data to disk (if writing)
  • Frees system resources
  • Avoids file corruption

๐Ÿ“ Summary

ActionMethod
Open file (write)ofstream out("file.txt");
Open file (read)ifstream in("file.txt");
Open with modefile.open("file.txt", mode);
Close filefile.close();