Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

[130014]: src / hugin_base / vigra_ext / FileRAII.h Maximize Restore History

Download this file

FileRAII.h    92 lines (84 with data), 2.6 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/** @file fileRAII.h
*
* @author Lukas Jirkovsky <l.jirkovsky@gmail.com>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <string>
#include <cstdio>
#include <cerrno>
#include <vigra/error.hxx>
namespace vigra_ext
{
/** Class used for opening files.
* File class using RAII (Resource Acquisition Is Initialization) technique.
* This ensures that the file is properly close even when an exception occurs.
*/
class FileRAII
{
public:
/** Open the specified file.
*
* \param path path to a file
* \param mode mode as defined by the fopen function
*/
FileRAII(const char *path, const char *mode)
{
file = std::fopen(path, mode);
if (file == 0) {
std::string msg("Unable to open file '");
msg += path;
msg += "'.";
vigra_precondition(0, msg.c_str());
}
}
~FileRAII()
{
if (file) {
errno = 0;
if (std::fclose(file)) {
// there are several possible errors, handle some of them
std::string msg;
switch(errno)
{
case EBADF:
msg = "Bad file descriptor.";
break;
case EIO:
msg = "An I/O error occurred while closing the file.";
break;
default:
msg = "An error ocured while closing the file.";
break;
}
vigra_postcondition(0, msg.c_str());
}
}
}
/** Get pointer to opened file.
* \return FILE* pointer to the opened file.
*/
FILE* get()
{
return file;
}
private:
FILE* file;
// this class should never be copied or assigned
FileRAII(const FileRAII &);
FileRAII& operator=(const FileRAII &);
};
}