Module 7 · Templates, Exceptions, Namespaces and Files — topic 4 of 4
File Handling
Read and write files with ifstream, ofstream and fstream: text lines, formatted values, CSV parsing, append mode, binary data and error checking.
Learning objectives
- Write and read text files with streams
- Parse CSV lines with stringstream
- Use append and binary modes and check for errors
Definition
C++ file I/O uses stream classes from<fstream>:std::ifstreamfor input,std::ofstreamfor output andstd::fstreamfor both. They support the same>>,<<andgetlineoperations as console streams and close automatically when destroyed.
Introduction
File streams behave just like std::cin and std::cout, so everything you know about stream operators applies. And because they are RAII objects, the file closes automatically at the end of the scope — no fclose to forget.
Why it matters
Every management-system project stores data in files.
Parsing CSV and log files is an everyday programming task.
Detailed explanation
std::ofstream out("data.txt"); creates or truncates; std::ios::app appends; std::ios::binary disables newline translation.
Check success with if (!in) or in.is_open(). After reading fails, the stream is in a fail state; reading loops test the read itself: while (std::getline(in, line)).
std::istringstream turns a line into a stream so you can split fields with getline(ss, field, ',').
Binary I/O: out.write(reinterpret_cast<const char*>(&value), sizeof value) and in.read(...) — only for trivially copyable types and with portability caveats.
std::filesystem (C++17) checks existence, sizes and directories: std::filesystem::exists("data.txt").
Syntax
- Include
<fstream>and<sstream>. - Never loop on
eof(); test the read operation. - Streams close in their destructors.
Code examples
Write then read lines
1. Classes 2. Templates 3. STL
Handling a missing file
could not open missing.txt
More examples
Parsing a CSV and appending results
3 students, average 81.3333 average: 81.3
Step-by-step explanation
- A temporary
std::ofstreamwrites the CSV and closes at the end of the statement. - The header line is skipped before parsing rows.
istringstreamsplits each row at the comma;stoiconverts marks.- The report is opened in append mode;
rdbuf()prints a whole file.
Expected output
Running “Parsing a CSV and appending results” prints exactly:
Practical applications
- Configuration loaders read key=value files.
- Data pipelines import and export CSV.
- Applications append to log files.
Best practices
- Check that every file opened successfully.
- Let RAII close files; keep stream scopes small.
- Prefer text formats for portability; document binary layouts.
Common mistakes
Looping on eof()
Avoid
Prefer
eof() becomes true only after a failed read, so the last line is processed twice.
Truncating a file you meant to extend
Avoid
Prefer
The default mode for ofstream truncates existing content.
Important notes
- Relative paths are resolved from the current working directory, not the executable's folder.
- Binary-writing structs is not portable across compilers or architectures.
Key takeaways
- ifstream reads, ofstream writes, fstream does both.
- Loop on
getline; never oneof(). - Use
std::ios::appto append.
Try it yourself
- 1Count lines, words and characters in a file given on the command line.
- 2Write a vector of structs to CSV and read it back into a new vector.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
4 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhich class reads from a file?
- BeginnerWhy does `while (!in.eof()) { std::getline(in, line); process(line); }` process the last line twice?
- ModerateWhich open mode adds data to the end of an existing file?