<fstream> gives you std::ofstream (write), std::ifstream (read) and std::fstream (both). They work exactly like cin/cout and close themselves (RAII).
Write, then read back
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
int main() {
{
std::ofstream out("scores.txt"); // truncates / creates
if (!out) { std::cerr << "cannot open\n"; return 1; }
out << "ada 91\n" << "bob 78\n" << "cy 85\n";
} // closed (and flushed) here
{
std::ofstream app("scores.txt", std::ios::app); // append mode
app << "dee 99\n";
}
std::ifstream in("scores.txt");
std::string name;
int score, total = 0, count = 0;
while (in >> name >> score) { // token-by-token
total += score;
++count;
}
std::cout << count << " students, average " << total / count << '\n';
in.clear(); // reset EOF flag…
in.seekg(0); // …and rewind
std::string line;
std::getline(in, line); // line-by-line
std::cout << "first line: " << line << '\n';
in.close();
std::remove("scores.txt");
}4 students, average 88
first line: ada 91| Mode flag | Meaning |
|---|---|
std::ios::in / std::ios::out | Read / write (defaults for ifstream / ofstream) |
std::ios::app | Every write goes to the end |
std::ios::trunc | Discard existing contents (default for ofstream) |
std::ios::binary | No newline translation (matters on Windows) |
std::ios::ate | Start at the end, but may seek anywhere |
Stream state
| Check | True when |
|---|---|
if (stream) / !stream.fail() | Last operation succeeded |
stream.eof() | Tried to read past the end |
stream.fail() | Format error or EOF (e.g. reading letters into an int) |
stream.bad() | Unrecoverable I/O error |
stream.clear() | Resets the flags so you can continue |
Binary files & whole-file reads
#include <cstdio>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
int main() {
std::vector<int> data{1, 2, 3, 1000000};
{
std::ofstream out("data.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(data.data()), data.size() * sizeof(int));
}
std::ifstream in("data.bin", std::ios::binary);
std::vector<int> back(4);
in.read(reinterpret_cast<char*>(back.data()), back.size() * sizeof(int));
std::cout << in.gcount() << " bytes, last = " << back[3] << '\n';
std::ofstream("note.txt") << "line one\nline two\n";
std::ifstream t("note.txt");
std::stringstream buffer;
buffer << t.rdbuf(); // slurp the whole file
std::cout << buffer.str().size() << " chars\n";
std::remove("data.bin");
std::remove("note.txt");
}16 bytes, last = 1000000
18 charsDo you need to call close() on an fstream?