-
-
Save david7482/624da7890d47215750c1 to your computer and use it in GitHub Desktop.
Using a C pointer (stdio) with a unique_ptr (C++11) (code from: https://codereview.stackexchange.com/questions/4679/shared-ptr-and-file-for-wrapping-cstdio-update-also-dlfcn-h)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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