Created
June 24, 2013 11:55
-
-
Save t-mat/5849549 to your computer and use it in GitHub Desktop.
unique_ptr for FILE*
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 <stdio.h> | |
#include <memory> | |
int main() { | |
std::unique_ptr<FILE, int(*)(FILE*)> fp(fopen("test.txt", "r"), fclose); | |
if(fp) { | |
char buf[4096]; | |
while(fgets(buf, sizeof(buf), fp.get())) { | |
printf("%s", buf); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about:
Then use it like this:
The pointer is just as big as a null-pointer. And you also get rid of the
error: ignoring attributes on template argument ‘int (*)(FILE*)’ [-Werror=ignored-attributes]
message.EDIT: Change
fclose
topclose
.