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
- Start with A
- Do this Write, then read
- Result A
#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);
}
A
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 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
#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;
}
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.