Text File Streams (ifstream & ofstream)
🟡 Intermediate
📖 Definition
The <fstream> header provides std::ofstream (file output stream) to write formatted text to disk and std::ifstream (file input stream) to read text files line by line using std::getline().
💡 Code Example
#include <iostream>
#include <fstream>
#include <string>
int main() {
// Write
{
std::ofstream outFile("sample.txt");
outFile << "Line 1: ISO C++17\nLine 2: Persistent Storage\n";
}
// Read
std::ifstream inFile("sample.txt");
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << "\n";
}
return 0;
}