C++ File Handling Tutorial
C++ file handling enables programs to store data persistently by reading from and writing to files. The `
Opening a File
Files can be opened in different modes using the `fstream`, `ifstream`, or `ofstream` classes:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream outFile("example.txt");
if (outFile.is_open()) {
cout << "File opened successfully for writing." << endl;
outFile.close();
} else {
cout << "Failed to open file." << endl;
}
return 0;
}
Writing to a File
Use the `ofstream` object to write data:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, File Handling in C++!" << endl;
outFile.close();
}
return 0;
}
Reading from a File
Use the `ifstream` object to read data:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream inFile("example.txt");
string content;
if (inFile.is_open()) {
while (getline(inFile, content)) {
cout << content << endl;
}
inFile.close();
}
return 0;
}
File Modes
Files can be opened in modes like `ios::app`, `ios::binary`, and `ios::trunc` for specific use cases.
Closing a File
Always close files using the `.close()` method to ensure data integrity.
Best Practices
- Always check if the file is open before performing operations.
- Use exception handling for robust file I/O.
×