I'm just beginning a book called C++ Crash Course by Josh Lospinoso, from No Starch Press. In the preface of the book, he addresses benefits from C++ that C-only developers can take advantage of if they compile their C code with a C++ compiler. Here's an approach that allows C code to use C++'s RAII idiom, and it won't leak the file handle in case something external to the code breaks (like the disk space is exhausted for example).
// demo of a SuperC file class, pp55-56
#include <cstdio>
#include <cstring>
#include <system_error>
struct File
{
File(const char* path, bool write) {
auto file_mode = write ? "w" : "r";
file_ptr = fopen(path, file_mode);
if (! file_ptr)
throw std::system_error{errno, std::system_category()};
}
~File() { fclose(file_ptr); }
Message too long. Click
here
to view full text.