File Handling and Exceptions

Article · 3:00

Reading and writing text and binary files with fstream, and using try, throw and catch where they actually belong.

File streams come from <fstream> and behave like cin and cout because they share a base. std::ifstream reads, std::ofstream writes, std::fstream does both. Construct one with a filename and it opens; let it go out of scope and it closes. That automatic close is RAII again, and it is why you will rarely see an explicit .close() in modern code.

Always check that the open worked. A stream converts to bool, so if (!file) { ... } is the test. Skipping it is the most common file-handling bug there is: the program carries on against a closed stream and silently does nothing.

Reading has three shapes. file >> word extracts one whitespace-delimited token. std::getline(file, line) reads a line, and while (std::getline(file, line)) is the loop you want for text, because it terminates correctly at end of file. For binary data, open with std::ios::binary and use .read() and .write() with a char* and a byte count - and be aware you are writing your machine's exact representation, so endianness and struct padding matter the moment another machine reads it back.

Exceptions are for errors a function cannot handle locally and the caller might. throw raises one, try marks the region, and catch handles it. The crucial rule: catch by const reference, catch (const std::exception& e). Catching by value slices a derived exception down to the base and loses the information you wanted.

What exceptions are not for is ordinary control flow. A file not existing is normal, and returning a status or a std::optional says so more honestly than throwing. Reserve throwing for the genuinely exceptional: a constructor that cannot establish its invariant, an allocation failure, a violated precondition.

The part that makes exceptions work in C++ is stack unwinding. When one is thrown, every object between the throw and the catch has its destructor run as the stack unwinds. That is why RAII and exceptions are the same idea viewed twice: because destruction is guaranteed, a file closes and memory frees on the way out of an error, without a single line of cleanup code. Code that frees things by hand is code that leaks the moment something throws.

One rule with no exceptions: never let a destructor throw. If one throws while the stack is already unwinding from another exception, the program terminates immediately.

#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <vector>

// A function that cannot sensibly handle the failure itself.
double safe_divide(double a, double b)
{
    if (b == 0.0) {
        throw std::invalid_argument{"division by zero"};
    }
    return a / b;
}

int main()
{
    // ---------------- Writing ----------------
    {
        std::ofstream out{"notes.txt"};      // opens on construction

        if (!out) {                          // ALWAYS check
            std::cerr << "could not open for writing\n";
            return 1;
        }

        out << "first line\n"
            << "second line\n"
            << 42 << '\n';

    }   // out goes out of scope here: flushed and closed. No .close() needed.

    // Append rather than truncate:
    std::ofstream log{"notes.txt", std::ios::app};

    // ---------------- Reading ----------------
    std::ifstream in{"notes.txt"};
    if (!in) {
        std::cerr << "could not open for reading\n";
        return 1;
    }

    std::string line;
    while (std::getline(in, line)) {     // the correct loop for text
        std::cout << "> " << line << '\n';
    }
    // Reading past the end sets the eof bit, which ends the loop. Writing
    // `while (!in.eof())` instead is the classic bug: eof is only set AFTER
    // a failed read, so the last line gets processed twice.

    // ---------------- Binary ----------------
    std::vector<int> numbers{1, 2, 3, 4};
    {
        std::ofstream bin{"data.bin", std::ios::binary};
        bin.write(reinterpret_cast<const char*>(numbers.data()),
                  static_cast<std::streamsize>(numbers.size() * sizeof(int)));
    }
    // Writing raw memory like this is fast and not portable: another
    // machine may order those bytes differently.

    // ---------------- Exceptions ----------------
    try {
        std::cout << safe_divide(10, 2) << '\n';   // 5
        std::cout << safe_divide(10, 0) << '\n';   // throws

        std::cout << "never reached\n";
    }
    catch (const std::invalid_argument& e) {   // most specific first
        std::cerr << "bad argument: " << e.what() << '\n';
    }
    catch (const std::exception& e) {          // then the base
        std::cerr << "error: " << e.what() << '\n';
    }
    catch (...) {                              // anything at all
        std::cerr << "unknown\n";
    }
    // catch (std::exception e)  -- by VALUE -- would slice a derived
    // exception down to its base and throw away what you needed.

    // Stack unwinding is why this is safe: if the body of the try had
    // opened files or built vectors, every one of their destructors runs
    // on the way to the catch. Nothing leaks, and no cleanup was written.

    return 0;
}

Discussion

No questions on this topic yet. Sign in to ask the first one.