FotoSHOCK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Pages
File.hpp
1 /*
2  * Copyright 2011, 2012 Lukas Jirkovsky
3  *
4  * This file is part of FotoSHOCKcore.
5  *
6  * FotoSHOCKcore is free software: you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation, version 3 of the License.
9  *
10  * FotoSHOCKcore is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public License
16  * along with FotoSHOCKcore. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #ifndef FILE_H
20 #define FILE_H
21 
22 #include "IOException.hpp"
23 
24 #include <string>
25 #include <cstdio>
26 #include <cerrno>
27 
28 namespace FotoSHOCKcore {
29 namespace IO {
30 
35 class File {
36  public:
38 
43  File (const char* path, const char* mode) throw (IOException) {
44  file = std::fopen (path, mode);
45  if (file == 0) {
46  std::string msg("Unable to open the file ");
47  msg += path;
48  msg += " with mode: ";
49  msg += mode;
50  throw IOException(msg.c_str(), __FILE__, __LINE__);
51  }
52  }
53 
55 
58  void close() throw (IOException) {
59  // it is not necessary to check for file != 0, as it is guaranteed by the constructor
60  errno = 0;
61  if (std::fclose (file)) {
62  // there are several possible errors, handle some of them
63  std::string msg;
64  switch (errno) {
65  case EBADF:
66  msg = "Bad file descriptor.";
67  break;
68  case EIO:
69  msg = "An I/O error occurred while closing the file.";
70  break;
71  default:
72  msg = "An error ocured while closing the file.";
73  break;
74  }
75  throw IOException(msg.c_str(), __FILE__, __LINE__);
76  }
77  file = 0;
78  }
79 
81 
89  ~File() {
90  // close the handle in case it is not closed yet
91  if (file) {
92  errno = 0;
93  if (std::fclose (file)) {
94  // there are several possible errors, handle some of them
95  switch (errno) {
96  case EBADF:
97  std::fprintf(stderr, "Bad file descriptor.");
98  break;
99  case EIO:
100  std::fprintf(stderr, "An I/O error occurred while closing the file.");
101  break;
102  default:
103  std::fprintf(stderr, "An error ocured while closing the file.");
104  break;
105  }
106  }
107  }
108  }
109 
111 
114  FILE* get() {
115  return file;
116  }
117 
118  private:
119  FILE* file;
120 
121  // this class should never be copied or assigned
122  File (const File&);
123  File& operator= (const File&);
124 };
125 
126 }
127 }
128 
129 #endif