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)
{
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 ...