Last active
February 8, 2025 07:12
-
-
Save meshell/876f1e01c7e72994b126 to your computer and use it in GitHub Desktop.
RAII example using unique_ptr
This file contains 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 <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