Skip to content

Instantly share code, notes, and snippets.

@plusangel
Created January 2, 2022 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plusangel/d1c91fad71f8eba142e5e5e150b2dc0c to your computer and use it in GitHub Desktop.
Save plusangel/d1c91fad71f8eba142e5e5e150b2dc0c to your computer and use it in GitHub Desktop.
RAII in modern C++ (example a)
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_1 raii_1.cpp)
#include <iostream>
#include <string>
#include <string_view>
struct OpenFile
{
OpenFile(std::string_view filename)
{
std::cout << "Opening the file" << std::endl;
// file_.exceptions(std::ifstream::failbit | std::ifstream::badbit);
file_ = fopen(filename.data(), "r");
if (file_ == NULL) {
throw std::runtime_error(std::strerror(errno));
}
}
std::string ReadLine()
{
char line[255];
fgets(line, sizeof(line), file_);
return std::string(line);
}
~OpenFile()
{
std::cout << "Closing the file" << std::endl;
fclose(file_);
}
private:
FILE *file_;
};
int main()
{
try {
OpenFile my_file{"ssample.txt"};
std::string line = my_file.ReadLine();
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