Automatic fclose() in C++11

This post is more of a mocking than serious advice, provided that a) STL includes <fstream> header with std::ifstream and std::ofstream classes, that do the same without any additional effort, and b) mixing templates and libC is just plain weird in my book.

C++11 added (among others) std::unique_ptr in <memory>, that uses std::default_delete template functor to free up objects when the pointer leaves its scope. By default, delete operator is called if the pointer is not NULL. But of course, you can always specialize a template:

#include <stdio.h>
#include <memory>

namespace std
{
    template<>
    struct default_delete<FILE>
    {
        void operator()(FILE* __ptr) const { fclose(__ptr); }
    };
}

int main()
{
    std::unique_ptr<FILE> in(fopen("test.txt", "wt"));
    // work with file via in.get() pointer using fwrite() etc.
    // no need to close the file explicitly...
    return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s