๐ 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 Class | Purpose |
---|---|
ifstream | Input file stream (read from file) |
ofstream | Output file stream (write to file) |
fstream | Input and output stream (read & write) |
๐ Opening a File in C++
To open a file, you create a stream object and use either:
- Constructor method
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()
:
Mode | Description |
---|---|
ios::in | Open for reading |
ios::out | Open for writing |
ios::app | Append to end of file |
ios::trunc | Truncate file if it exists |
ios::binary | Open 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
Action | Method |
---|---|
Open file (write) | ofstream out("file.txt"); |
Open file (read) | ifstream in("file.txt"); |
Open with mode | file.open("file.txt", mode); |
Close file | file.close(); |