📂 File Handling in C++
File handling in C++ is performed using streams from the <fstream>
library. You can use it to read from or write to text files. Commonly used classes are ofstream
for writing and ifstream
for reading.
📘 Key File Stream Classes
- ifstream: Read from files
- ofstream: Write to files
- fstream: Read and write from/to files
📄 C++ Code: Write and Read a Text File
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// Writing to a file
ofstream writeFile("example.txt");
if (writeFile.is_open()) {
writeFile << "Hello, world!" << endl;
writeFile << "This is a text file." << endl;
writeFile.close();
} else {
cout << "Unable to open file for writing." << endl;
}
// Reading from the file
ifstream readFile("example.txt");
string line;
cout << "Reading from file:" << endl;
if (readFile.is_open()) {
while (getline(readFile, line)) {
cout << line << endl;
}
readFile.close();
} else {
cout << "Unable to open file for reading." << endl;
}
return 0;
}
📝 Sample Output
Reading from file:
Hello, world!
This is a text file.
Hello, world!
This is a text file.
🧠 Explanation
ofstream
creates or overwrites a file and writes text into it.ifstream
reads the file line by line usinggetline()
.- Always check if a file is open before reading or writing.
- Use
close()
to close the file after operations are done.
File I/O is essential for programs that need to save data persistently. It's used in databases, logging, configuration, and more.
Post a Comment