S5.0 What This Teaches
std::ofstreamfor writingstd::ifstreamfor reading- Reading line-by-line with
std::getline - Reading the whole file at once
- Appending to an existing file
- Checking stream state
S5.1 Writing with ofstream
#include <fstream>
{
std::ofstream out("output.txt");
if (!out) throw std::runtime_error("cannot open file");
out << "line one\n";
out << "line two\n";
} // RAII: file closed automatically when out goes out of scope
ofstream truncates the file if it already exists. The file is
closed when the stream object is destroyed - no explicit close()
call is needed.
S5.2 Reading Line by Line
#include <fstream>
#include <string>
std::ifstream in("output.txt");
if (!in) throw std::runtime_error("cannot open file");
std::string line;
while (std::getline(in, line)) {
std::cout << line << "\n";
}
std::getline reads one line at a time, stripping the newline.
The while loop terminates when getline returns a falsy stream
(EOF or error).
S5.3 Reading the Whole File
#include <fstream>
#include <sstream>
std::ifstream in("output.txt");
std::ostringstream buf;
buf << in.rdbuf(); // reads entire file into string stream
std::string content = buf.str();
rdbuf() returns a pointer to the stream buffer; inserting it
into another stream copies all remaining data. This is the idiomatic one-liner
for reading an entire file into a string.
S5.4 Appending to a File
std::ofstream app("output.txt", std::ios::app);
app << "appended line\n";
std::ios::app opens in append mode: all writes go to the end
of the file and existing content is preserved.
S5.5 Checking Stream State
std::ifstream in("missing.txt");
if (!in) std::cout << "failed to open\n";
if (in.fail()) std::cout << "fail bit set\n";
if (in.eof()) std::cout << "at end of file\n";
if (in.bad()) std::cout << "bad bit set (IO error)\n";
if (in.good()) std::cout << "stream ok\n";
if (!stream) is the standard idiom.
S5.6 Example - All Together
// FileIO - ofstream, ifstream, getline, fstream.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main() {
const std::string filename = "demo.txt";
// write
{
std::ofstream out(filename);
if (!out) { std::cerr << "open failed\n"; return 1; }
out << "line one\n" << "line two\n" << "line three\n";
}
// read whole file
{
std::ifstream in(filename);
std::ostringstream buf;
buf << in.rdbuf();
std::cout << buf.str();
}
// append
{
std::ofstream app(filename, std::ios::app);
app << "line four\n";
}
// read line by line
{
std::ifstream in(filename);
std::string line;
int n = 0;
while (std::getline(in, line))
std::cout << ++n << ": " << line << "\n";
}
return 0;
}
line one
line two
line three
1: line one
2: line two
3: line three
4: line four
S5.7 Exercise
Exercise
- Write a program that reads a text file line by line, counts the total number of words across all lines (split on whitespace), and prints the count.
- Write a CSV row to a file using
ofstream, then read it back and split on','to recover the fields. - Copy one file to another by reading the source with
rdbuf()and writing to a newofstream.
S5.8 Common Mistakes
Not checking if the file opened
std::ifstream in("missing.txt");
std::string line;
std::getline(in, line); // silent failure; line is empty
if (!in) immediately after construction.Reading after EOF without clearing the error
while (!in.eof()) { // wrong: last iteration reads empty
std::getline(in, line);
process(line);
}
// correct:
while (std::getline(in, line))
process(line);
Forgetting ios::app and overwriting the file
ofstream truncates it.
Use std::ios::app to preserve existing content.
S5.9 Key Terms
| Term | Meaning |
|---|---|
| ofstream | Output file stream; write text to a file |
| ifstream | Input file stream; read text from a file |
| fstream | Read-write file stream |
| getline(stream, s) | Reads one line into s; returns the stream (falsy at EOF) |
| rdbuf() | Returns the stream buffer; inserting it copies all remaining data |
| ios::app | Open flag: append to file rather than truncate |
| ios::binary | Open flag: read/write binary data without newline translation |
| fail(), eof(), bad() | Stream state flags indicating error conditions |