C++ file I/O through stream classes. Files close automatically when the object goes out of scope (RAII). ifstream reads, ofstream writes, fstream does both.
Include: #include <fstream> | Namespace: std | Compile: g++ -Wall -std=c++17 ...
| Name | Type / Signature | Description |
|---|---|---|
| std::ifstream | class : istream | Input file stream (reading) |
| std::ofstream | class : ostream | Output file stream (writing) |
| std::fstream | class : iostream | Bidirectional file stream |
| fs.open(path, mode) | void | Open file; mode = ios::in | ios::out | ios::app | ios::binary |
| fs.close() | void | Close the file |
| fs.is_open() | bool | True if file was opened successfully |
| fs.good() | bool | True if no error flags set |
| fs.eof() | bool | True if end-of-file reached |
| fs.fail() | bool | True if a non-fatal error occurred |
| fs >> x | istream & | Extract next token from file |
| fs << x | ostream & | Write x to file |
| getline(fs, str) | istream & | Read a full line into str |
| fs.seekg(pos) | istream & | Set read position |
| fs.seekp(pos) | ostream & | Set write position |
| ios::in | openmode | Open for reading |
| ios::out | openmode | Open for writing (truncates) |
| ios::app | openmode | Append to end of file |
| ios::binary | openmode | Open in binary mode |
Copy, save as demo.cpp, and compile with the command at the bottom.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main() {
{ // Write
ofstream out("students.txt");
if (!out) { cerr << "Cannot open for writing\n"; return 1; }
out << "Alice 95\nBob 87\nCarol 92\n";
} // file closes here (RAII)
{ // Read line by line
ifstream in("students.txt");
string line;
cout << "Contents:\n";
while (getline(in, line)) cout << " " << line << "\n";
}
{ // Append
ofstream app("students.txt", ios::app);
app << "Dave 78\n";
}
// Parse into struct
struct Student { string name; int score; };
vector<Student> students;
ifstream in2("students.txt");
string name; int score;
while (in2 >> name >> score) students.push_back({name, score});
cout << "\nParsed " << students.size() << " students.\n";
for (auto &s : students)
cout << " " << s.name << " => " << s.score << "\n";
return 0;
}
// Compile: g++ -Wall -std=c++17 -o fstream_demo fstream_demo.cpp