Is there any RAII file already implemented?

The RAII file file looks pretty simple, so I assume it is already implemented? But I could not find any implementation. I found file_descriptor in boost :: iostreams, but I don't know, this is what I am looking for.

+4
source share
3 answers

std::fstream support for use in the RAII style - they can be opened and even tested during construction, and they are automatically cleared and closed in the destructor, although you can skip errors if you assume that this works, so you might want to do something more explicit in the code if you need reliability.

For instance:

if (std::ifstream input(filename))
    ... use input...
else
    std::cerr << "unable to open '" << filename << "'\n";

, - . , -, close, , - ....

struct Descriptor
{
    Descriptor(int fd, const char* filename = nullptr)
      : fd_(fd), filename_(filename)
    {
        if (fd < 0)
        {
            std::ostringstream oss;
            oss << "failed to open file";
            if (filename_) oss << " '" << filename_ << '\'';
            oss << ": " << strerror(errno);
            throw std::runtime_error(oss.str());
        }
    }
    ~Descriptor()
    {
        if (fd_ != -1 && close(fd_) == -1)
        {
            // throwing from destructors risks termination - avoid...
            std::cerr << "failed to close file";
            if (filename_) std::cerr << " '" << filename_ << '\'';
            std::cerr << ": " << strerror(errno) << std::endl;
        }
    }
    operator int() const { return fd_; }

  private:
    int fd_;
};

:

try
{
    Descriptor fd(open(filename, O_RDONLY), filename);
    int nbytes = read(fd, ...);
    ...
}
catch ...
+5

, .

, :

std::unique_pointer<HANDLETYPE, closehandletypefunction> smartpointer;

++ , , , .

0

boost::filesystem::ifstream ( ofstream ).

, , , file.close()

:

, , -.

, :)

0

Source: https://habr.com/ru/post/1534348/


All Articles