92b0b19d53380590fb2071b43d646612a45a058b
[dcpomatic.git] / src / lib / data.cc
1 /*
2     Copyright (C) 2015 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "data.h"
21 #include "cross.h"
22 #include "exceptions.h"
23
24 #include "i18n.h"
25
26 using boost::shared_array;
27
28 Data::Data ()
29         : _size (0)
30 {
31
32 }
33
34 Data::Data (int size)
35         : _data (new uint8_t[size])
36         , _size (size)
37 {
38
39 }
40
41 Data::Data (uint8_t const * data, int size)
42         : _data (new uint8_t[size])
43         , _size (size)
44 {
45         memcpy (_data.get(), data, size);
46 }
47
48 Data::Data (boost::filesystem::path file)
49 {
50         _size = boost::filesystem::file_size (file);
51         _data.reset (new uint8_t[_size]);
52
53         FILE* f = fopen_boost (file, "rb");
54         if (!f) {
55                 throw FileError (_("could not open file for reading"), file);
56         }
57         
58         size_t const r = fread (_data.get(), 1, _size, f);
59         if (r != size_t (_size)) {
60                 fclose (f);
61                 throw FileError (_("could not read from file"), file);
62         }
63                 
64         fclose (f);
65 }
66
67 void
68 Data::write (boost::filesystem::path file) const
69 {
70         FILE* f = fopen_boost (file, "wb");
71         if (!f) {
72                 throw WriteFileError (file, errno);
73         }
74         size_t const r = fwrite (_data.get(), 1, _size, f);
75         if (r != size_t (_size)) {
76                 fclose (f);
77                 throw FileError ("could not write to file", file);
78         }
79         fclose (f);
80 }
81
82 void
83 Data::write_via_temp (boost::filesystem::path temp, boost::filesystem::path final) const
84 {
85         write (temp);
86         boost::filesystem::rename (temp, final);
87 }