#ifndef FILEWRAPPER_HPP #define FILEWRAPPER_HPP /* Part of Underdog. https://underdog.sourceforge.net * Released under GPLv3. Other licenses may be available. * Robert White © Copyright 2014 */ #include #include #include #include #include #include struct FileWrapper { struct BadFile: public std::exception { }; FileWrapper(std::string name, int flags, int base = AT_FDCWD): FileDescriptor(openat(base,name.c_str(),flags)) { if (FileDescriptor == -1) { throw BadFile(); } } explicit FileWrapper(const FileWrapper & X): FileDescriptor(dup(X.FileDescriptor)) { if (FileDescriptor == -1) { throw BadFile(); } } explicit FileWrapper(int other_fd): FileDescriptor(dup(other_fd)) { if (FileDescriptor == -1) { throw BadFile(); } } FileWrapper(int other_fd, int new_fd): FileDescriptor(dup2(other_fd,new_fd)) { if (FileDescriptor == -1) { throw BadFile(); } } void Replace(const FileWrapper & X) { int newfd = dup(X.FileDescriptor); if (newfd != -1) { close(FileDescriptor); FileDescriptor = newfd; } } ~FileWrapper() { close(FileDescriptor); } operator int() const { return FileDescriptor; } int fd() const { return FileDescriptor; } protected: int FileDescriptor; private: FileWrapper & operator =(const FileWrapper & X); }; #endif