Skip to content

Chapter 26 of 31

File Handling

Read, write, append, seek, validate streams, and design portable serialization.

36 minutes 10 quick checksBy Subha Prasad
Lesson 26 of 31Course navigation

Lesson content

Read, practise, then check your understanding

std::ifstream reads files, std::ofstream writes files, and std::fstream can do both. Stream objects close their files in destructors, so local streams follow RAII.

#include <fstream>
#include <string>

std::ofstream log{"events.log", std::ios::app};
if (!log) throw std::runtime_error{"cannot open log"};
log << "course opened\n";

std::ifstream input{"events.log"};
for (std::string line; std::getline(input, line); ) {
    // process a complete line
}
if (!input.eof()) throw std::runtime_error{"read failed"};

Check the operation that reads rather than looping on !eof(): end-of-file becomes known only after a read attempts to pass it. Stream state flags include good, eof, fail, and bad; clear() resets flags.

Modes and positions

Combine std::ios::in, out, app, trunc, ate, and binary as needed. seekg/tellg control the input position; seekp/tellp control output. Binary mode prevents platform text translation but does not make raw object dumps portable.

Portable serialization defines field order, widths, byte order, encoding, versioning, and validation. Class padding, pointer values, and implementation-specific layouts must never be persisted directly. Write to a temporary file and rename it for important atomic-style updates, handle permission and disk-full failures, and verify buffered output after flush or close when durability matters.

Knowledge check

Answer every question correctly to complete this chapter.

Which type reads from a file?
Which type writes to a file?
Which open mode appends?
How should stream extraction be looped?
Which function reads an entire text line?
Which flag opens binary mode?
What should code verify after opening a stream?
Why avoid raw object dumps as portable serialization?
What does seekg control?
Why can output failure appear during close or flush?

0 of 10 checks passed

Your progress is saved on this device.