Created
January 2, 2022 15:54
-
-
Save plusangel/052973b7349907b33d0f82b12978f1a1 to your computer and use it in GitHub Desktop.
RAII example in modern C++ (example b)
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
cmake_minimum_required(VERSION 3.0.0) | |
project(raii_examples VERSION 0.1.0) | |
set(CMAKE_CXX_STANDARD 17) | |
set(CMAKE_CXX_STANDARD_REQUIRED ON) | |
set(CMAKE_CXX_EXTENSIONS OFF) | |
add_executable(raii_2 raii_2.cpp) |
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 <fstream> | |
#include <memory> | |
#include <string_view> | |
#include <iostream> | |
void releaseFile(FILE *file) | |
{ | |
std::cout << "Closing the file" << std::endl; | |
std::fclose(file); | |
} | |
using FileRaii = std::unique_ptr<std::FILE, decltype(&releaseFile)>; | |
FileRaii acquireFile(std::string_view filename) | |
{ | |
std::cout << "Opening the file" << std::endl; | |
FileRaii my_file{std::fopen(filename.data(), "r"), &releaseFile}; | |
if (my_file == NULL) | |
{ | |
throw std::runtime_error(std::strerror(errno)); | |
} | |
return my_file; | |
} | |
int main() | |
{ | |
try | |
{ | |
auto f = acquireFile("sample.txt"); | |
char line[255]; | |
fgets(line, sizeof(line), f.get()); | |
std::cout << line << std::endl; | |
} | |
catch (std::runtime_error &e) | |
{ | |
std::cerr << e.what() << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment