FileRAII.h

Go to the documentation of this file.
00001 
00021 #include <string>
00022 #include <cstdio>
00023 #include <cerrno>
00024 
00025 #include <vigra/error.hxx>
00026 
00027 namespace vigra_ext
00028 {
00033 class FileRAII
00034 {
00035 public:
00041     FileRAII(const char *path, const char *mode)
00042     {
00043         file = std::fopen(path, mode);
00044         if (file == 0) {
00045             std::string msg("Unable to open file '");
00046             msg += path;
00047             msg += "'.";
00048             vigra_precondition(0, msg.c_str());
00049         }
00050     }
00051 
00052     ~FileRAII()
00053     {
00054         if (file) {
00055             errno = 0;
00056             if (std::fclose(file)) {
00057                 // there are several possible errors, handle some of them
00058                 std::string msg;
00059                 switch(errno)
00060                 {
00061                     case EBADF:
00062                         msg = "Bad file descriptor.";
00063                         break;
00064                     case EIO:
00065                         msg = "An I/O error occurred while closing the file.";
00066                         break;
00067                     default:
00068                         msg = "An error ocured while closing the file.";
00069                         break;
00070                 }
00071                 vigra_postcondition(0, msg.c_str());
00072             }
00073         }
00074     }
00075 
00079     FILE* get()
00080     {
00081         return file;
00082     }
00083 
00084 private:
00085     FILE* file;
00086 
00087     // this class should never be copied or assigned
00088     FileRAII(const FileRAII &);
00089     FileRAII& operator=(const FileRAII &);
00090 };
00091 
00092 }

Generated on 21 Jan 2018 for Hugintrunk by  doxygen 1.4.7