Skip to content

Instantly share code, notes, and snippets.

@david7482
Forked from armornick/cfileptr.cpp
Created March 7, 2016 13:55
Show Gist options
  • Save david7482/624da7890d47215750c1 to your computer and use it in GitHub Desktop.
Save david7482/624da7890d47215750c1 to your computer and use it in GitHub Desktop.
#include <memory>
#include <cstdio>
/////////////////////////////////////////////////////////////////////////////
typedef std::unique_ptr<std::FILE, int (*)(std::FILE *)> unique_file_ptr;
typedef std::shared_ptr<std::FILE> shared_file_ptr;
static shared_file_ptr make_shared_file(const char * filename, const char * flags)
{
std::FILE * const fp = std::fopen(filename, flags);
return fp ? shared_file_ptr(fp, std::fclose) : shared_file_ptr();
}
static unique_file_ptr make_file(const char * filename, const char * flags)
{
return unique_file_ptr(std::fopen(filename, flags), std::fclose);
}
/////////////////////////////////////////////////////////////////////////////
int main(int argc, char const *argv[])
{
unique_file_ptr f = make_file("test.txt", "a");
std::fputs("And I heard, as it were, the noise of thunder:\n", f.get());
std::fputs("One of the four beasts saying\n", f.get());
std::fputs("Come and see\n", f.get());
std::fputs("And I saw.\n", f.get());
std::fputs("And behold, a white horse.\n", f.get());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment