1. Goals
Read and write text files with
ifstreamandofstream.Distinguish opening failures, invalid records and normal end of file.
Check writing, flushing and closing before reporting success.
Preserve current data when a replacement file is invalid.
2. Prerequisites
You know string, vector, streams, input validation and RAII.
Functions receiving istream& or ostream& borrow the caller's stream;
they do not own it and do not close it.
3. Explanation
The example stores study-session lengths. Each line contains exactly one
integer from 1 to 120. Surrounding whitespace is accepted; blank lines,
25abc, 25 40, overflowing numbers and out-of-range values are invalid.
An empty file represents an empty list. The final line need not end in
a newline character.
readMinutes uses getline, then an istringstream to parse each line
independently. After the number, std::ws skips whitespace; anything before
the end of the line is unwanted extra input. A bad record cannot trap the
next iteration on the same character.
Do not write while (!input.eof()): EOF describes a read that already
happened, not the next read. Attempt extraction in the loop condition.
At the end, a getline that extracts nothing may set both eofbit and
failbit; this can be normal termination. bad(), or stopping without
EOF, means a reading failure here. A stream already in a failed state
is rejected on entry. See C++17 getline.
New data is collected in candidate. Only a fully successful read swaps
it with the caller's vector. A valid first line followed by an invalid
second line therefore preserves the original data. Successfully loading
an empty file replaces the old data with an empty list, by design.
An ifstream owns the input-file resource; an ofstream owns the
output-file resource. Leaving scope closes the file, including on early
return. Destruction, however, does not return a save result.
writeMinutes validates, writes and calls flush(); saveMinutes
also calls close() and checks the state. Buffer synchronization or
closing failures must make the save fail. See
flush and
close.
Separating stream processing from path opening lets you test bad input
with istringstream and output with ostringstream, without creating
a file per test. The example uses default stream exception settings:
I/O errors set state flags. If a caller enables exceptions(), stream
errors can throw; allocation failures are not converted to false either.
saveMinutes validates every number before opening the file. Nevertheless,
successful opening with trunc discards its previous contents. A write
failure can leave a partial file; RAII does not restore the original.
Successful flush and close do not guarantee survival of a power failure.
This is a small, single-process file example, not an atomic update mechanism
for important data.
4. Runnable example
Save the code as main.cpp and compile as C++17. Run it in a separate
practice directory: it creates or overwrites notes-demo.txt in the
working directory. Do not run it where that filename contains data you
need to keep. No keyboard input is required.
#include <fstream>
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>
#include <string>
#include <vector>
bool validMinutes(const std::vector<int>& minutes) {
for (int value : minutes) {
if (value < 1 || value > 120) {
return false;
}
}
return true;
}
bool readMinutes(std::istream& input, std::vector<int>& minutes) {
if (!input) {
return false;
}
std::vector<int> candidate;
std::string line;
while (std::getline(input, line)) {
std::istringstream row(line);
int value = 0;
if (!(row >> value) || value < 1 || value > 120) {
return false;
}
row >> std::ws;
if (!row.eof()) {
return false;
}
candidate.push_back(value);
}
if (input.bad() || !input.eof()) {
return false;
}
minutes.swap(candidate);
return true;
}
bool writeMinutes(std::ostream& output, const std::vector<int>& minutes) {
if (!output || !validMinutes(minutes)) {
return false;
}
for (int value : minutes) {
output << value << '\n';
}
output.flush();
return static_cast<bool>(output);
}
bool loadMinutes(const std::string& path, std::vector<int>& minutes) {
std::ifstream input(path);
return input && readMinutes(input, minutes);
}
bool saveMinutes(const std::string& path, const std::vector<int>& minutes) {
if (!validMinutes(minutes)) {
return false;
}
std::ofstream output(path, std::ios::trunc);
if (!output) {
return false;
}
const bool written = writeMinutes(output, minutes);
output.close();
return written && static_cast<bool>(output);
}
int main() {
const std::string path = "notes-demo.txt";
const std::vector<int> planned{25, 40};
if (!saveMinutes(path, planned)) {
std::cerr << "Could not save demo file\n";
return 1;
}
std::vector<int> loaded;
if (!loadMinutes(path, loaded)) {
std::cerr << "Could not load demo file\n";
return 1;
}
std::cout << "Saved: " << path << '\n';
std::cout << "Minutes:";
for (int value : loaded) {
std::cout << ' ' << value;
}
std::cout << '\n';
std::istringstream malformed("30\nwrong\n");
std::cout << std::boolalpha
<< "Malformed accepted: " << readMinutes(malformed, loaded) << '\n';
std::cout << "Still loaded:";
for (int value : loaded) {
std::cout << ' ' << value;
}
std::cout << '\n';
return 0;
}Output when writing and reading succeed:
Saved: notes-demo.txt
Minutes: 25 40
Malformed accepted: false
Still loaded: 25 40The file contains two lines: 25 and 40. Relative paths start at the
program's working directory, not automatically at the source directory.
If opening, writing or reading fails, the program reports an error and
returns exit code 1.
5. Common mistakes
Checking only opening, then claiming success despite a write, flush or close error.
Looping on
!eof()and processing an old value after extraction fails.Reading numbers from the whole file without rejecting leftover text.
Clearing current data at the start of a load, then losing it on a bad line.
Expecting automatic cleanup to undo writes or guarantee power-loss durability.
Opening an important file with
truncjust to try the example.
6. Practice
Use
istringstreamto test"1\n120", empty input and" 25 \n". All must succeed. Use a fresh stream for each test.Start with
{25, 40}, then try"30\nwrong\n","0\n","121\n","25abc\n","25 40\n"and"\n". Each must returnfalsewhile preserving the two original values.Write
{10, 20}to anostringstream; expect"10\n20\n". A vector containing0must fail before appending any characters.In a practice directory, load a nonexistent path and verify old data is unchanged. Save to a path whose parent directory does not exist; it must fail. Explain why this does not simulate every possible disk error.
7. Self-check
Why does
failbitafter the loop not necessarily mean a damaged file? Answer: reading after the final line can extract nothing and set bothfailbitandeofbit. This example accepts normal EOF but rejectsbadbitor stopping before EOF; record validation is a separate check.Does an invalid second line change the old vector? Answer: no. Reading modifies a temporary vector; the final swap only happens after the entire file is accepted.
Why check
close()when RAII already exists? Answer: RAII releases the resource. Checking close lets the caller detect a failed final operation before reporting success; it does not guarantee atomic updates or survival of power loss.
Sample code
Source file
cpp98_foundation/26_file_io/main.cpp
#include <fstream>
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>
#include <string>
#include <vector>
bool validMinutes(const std::vector<int>& minutes) {
for (int value : minutes) {
if (value < 1 || value > 120) {
return false;
}
}
return true;
}
bool readMinutes(std::istream& input, std::vector<int>& minutes) {
if (!input) {
return false;
}
std::vector<int> candidate;
std::string line;
while (std::getline(input, line)) {
std::istringstream row(line);
int value = 0;
if (!(row >> value) || value < 1 || value > 120) {
return false;
}
row >> std::ws;
if (!row.eof()) {
return false;
}
candidate.push_back(value);
}
if (input.bad() || !input.eof()) {
return false;
}
minutes.swap(candidate);
return true;
}
bool writeMinutes(std::ostream& output, const std::vector<int>& minutes) {
if (!output || !validMinutes(minutes)) {
return false;
}
for (int value : minutes) {
output << value << '\n';
}
output.flush();
return static_cast<bool>(output);
}
bool loadMinutes(const std::string& path, std::vector<int>& minutes) {
std::ifstream input(path);
return input && readMinutes(input, minutes);
}
bool saveMinutes(const std::string& path, const std::vector<int>& minutes) {
if (!validMinutes(minutes)) {
return false;
}
std::ofstream output(path, std::ios::trunc);
if (!output) {
return false;
}
const bool written = writeMinutes(output, minutes);
output.close();
return written && static_cast<bool>(output);
}
int main() {
const std::string path = "notes-demo.txt";
const std::vector<int> planned{25, 40};
if (!saveMinutes(path, planned)) {
std::cerr << "Could not save demo file\n";
return 1;
}
std::vector<int> loaded;
if (!loadMinutes(path, loaded)) {
std::cerr << "Could not load demo file\n";
return 1;
}
std::cout << "Saved: " << path << '\n';
std::cout << "Minutes:";
for (int value : loaded) {
std::cout << ' ' << value;
}
std::cout << '\n';
std::istringstream malformed("30\nwrong\n");
std::cout << std::boolalpha
<< "Malformed accepted: " << readMinutes(malformed, loaded) << '\n';
std::cout << "Still loaded:";
for (int value : loaded) {
std::cout << ' ' << value;
}
std::cout << '\n';
return 0;
}