Hugintrunk  0.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
FileRAII.h
Go to the documentation of this file.
1 
21 #include <string>
22 #include <cstdio>
23 #include <cerrno>
24 
25 #include <vigra/error.hxx>
26 
27 namespace vigra_ext
28 {
33 class FileRAII
34 {
35 public:
41  FileRAII(const char *path, const char *mode)
42  {
43  file = std::fopen(path, mode);
44  if (file == 0) {
45  std::string msg("Unable to open file '");
46  msg += path;
47  msg += "'.";
48  vigra_precondition(0, msg.c_str());
49  }
50  }
51 
53  {
54  if (file) {
55  errno = 0;
56  if (std::fclose(file)) {
57  // there are several possible errors, handle some of them
58  std::string msg;
59  switch(errno)
60  {
61  case EBADF:
62  msg = "Bad file descriptor.";
63  break;
64  case EIO:
65  msg = "An I/O error occurred while closing the file.";
66  break;
67  default:
68  msg = "An error ocured while closing the file.";
69  break;
70  }
71  vigra_postcondition(0, msg.c_str());
72  }
73  }
74  }
75 
79  FILE* get()
80  {
81  return file;
82  }
83 
84 private:
85  FILE* file;
86 
87  // this class should never be copied or assigned
88  FileRAII(const FileRAII &);
89  FileRAII& operator=(const FileRAII &);
90 };
91 
92 }
FileRAII(const char *path, const char *mode)
Open the specified file.
Definition: FileRAII.h:41
FileRAII & operator=(const FileRAII &)
Class used for opening files.
Definition: FileRAII.h:33