Skip to content

Instantly share code, notes, and snippets.

@meshell
Last active February 22, 2016 20:21
Show Gist options
  • Save meshell/876f1e01c7e72994b126 to your computer and use it in GitHub Desktop.
Save meshell/876f1e01c7e72994b126 to your computer and use it in GitHub Desktop.
RAII example using unique_ptr
#include <cstdio>
#include <cstdlib>
#include <memory>
int main()
{
auto file_open = [](const char* filename, const char* mode) -> FILE*
{
return std::fopen(filename, mode);
};
auto file_deleter=[](FILE* file) {
std::puts("Close file\n");
std::fclose(file);
};
// Using a unique pointer and custom deleter (lamda)
std::unique_ptr<FILE, decltype(file_deleter)> fp{file_open("test.txt", "r"),
file_deleter};
if(!fp) {
std::perror("File opening failed");
return EXIT_FAILURE;
}
int c{};
while ((c = std::fgetc(fp.get())) != EOF) {
std::putchar(c);
}
if (std::ferror(fp.get())) {
std::puts("I/O error when reading");
return EXIT_FAILURE;
} else if (std::feof(fp.get())) {
std::puts("End of file reached successfully");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment