Lesson contents

C++ — File lifetime and automatic cleanup

In C++, a unique_ptr with a file-closing deleter can manage a C stream. Leaving its scope releases the stream even when a read or write returns an error.

A simple example

Read back one letter

  1. Start with A
  2. Do this Write, then read
  3. Result A
A file stores the letter between the write and the read.
lesson.cpp
#include <iostream>
#include <cstdio>

int main() {
    auto file = std::tmpfile();
    if (!file) return 1;
    std::fputc('A', file);
    std::rewind(file);
    std::cout << static_cast<char>(std::fgetc(file)) << '\n';
    std::fclose(file);
}
Output
A
Advertisements

Sum two lines from a temporary report

The unique_ptr owns a FILE with fclose as its deleter. It closes the stream even on an early return. Check the read result to distinguish an invalid token from the end of the report.

Morning returns: 4. Afternoon returns: 7. End of day: 11.
Read a two-line count sheet

Morning staff record four returns in a file and afternoon staff record seven on the next line. Read each line as a number and add it to the running total. The day ends with eleven returns.

Run the example

C++17. Run these commands from the directory containing the example. Use a Unix-style shell.

c++ -std=c++17 lesson.cpp -o lesson
./lesson
lesson.cpp
#include <iostream>
#include <cstdio>
#include <memory>

int main() {
    std::unique_ptr<std::FILE, decltype(&std::fclose)> file(std::tmpfile(), &std::fclose);
    if (!file) return 1;
    if (std::fputs("4\n7\n", file.get()) == EOF || std::fseek(file.get(), 0, SEEK_SET) != 0) {
        return 1;
    }
    int total = 0, value = 0, result = 0;
    while ((result = std::fscanf(file.get(), "%d", &value)) == 1) total += value;
    if (result != EOF || std::ferror(file.get())) return 1;
    std::cout << total << '\n';
    return 0;
}
Output
11

The file contains two whole-number readings on separate lines. Reading from the beginning gives 4 and 7, for a total of 11. The example creates its own file, so it can run in a clean working directory.

Try it yourself

Add a third line containing 12.

Check your answer

The new total is 23. This report format assumes valid integer readings. When accepting external input, apply the validation techniques from the preceding lesson.

C++ language and library reference

Related tags

  • C++
  • files
  • streams
  • resource management