C++ File Handling
File handling in C++ allows programs to read from and write to files. C++ provides classes in the <fstream> library for working with files: ofstream for writing, ifstream for reading, and fstream for both reading and writing.
File Opening Modes
- Always close files after opening them to free resources.
- Use ofstream to write, ifstream to read, and fstream for both operations.
- Check if the file opened successfully using
if(!file).
Next Topic
Next, learn about Namespaces in C++.
- ios::out – Open file for writing (creates a new file if it doesn’t exist).
- ios::in – Open file for reading.
- ios::app – Append data to the end of the file.
- ios::binary – Open file in binary mode.
Example: Writing to a File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("example.txt"); // Create and open file for writing
if(!outFile) {
cout << "Error opening file!" << endl;
return 1;
}
outFile << "Hello, C++ File Handling!" << endl;
outFile << "This is a second line." << endl;
outFile.close(); // Close the file
cout << "Data written to file successfully." << endl;
return 0;
}
Example: Reading from a File
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("example.txt"); // Open file for reading
if(!inFile) {
cout << "Error opening file!" << endl;
return 1;
}
string line;
while(getline(inFile, line)) {
cout << line << endl;
}
inFile.close(); // Close the file
return 0;
}
Output (Reading)
Hello, C++ File Handling! This is a second line.
Important Notes
- Always close files after opening them to free resources.
- Use ofstream to write, ifstream to read, and fstream for both operations.
- Check if the file opened successfully using
if(!file).
Next Topic
Next, learn about Namespaces in C++.