RawSpeed
fast raw decoding library
Loading...
Searching...
No Matches
FileWriter.cpp
Go to the documentation of this file.
1/*
2 RawSpeed - RAW file decoder.
3
4 Copyright (C) 2009-2014 Klaus Post
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with this library; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19*/
20
21#include "io/FileWriter.h"
22#include "io/Buffer.h"
23#include "io/FileIOException.h"
24#include <algorithm>
25#include <cstdint>
26#include <cstdio>
27
28#if !defined(__unix__) && !defined(__APPLE__)
29#ifndef NOMINMAX
30#define NOMINMAX // do not want the min()/max() macros!
31#endif
32
33#include "io/FileIO.h"
34#include <Windows.h>
35#include <io.h>
36#include <tchar.h>
37#endif // !defined(__unix__) && !defined(__APPLE__)
38
39namespace rawspeed {
40
41FileWriter::FileWriter(const char* _filename) : mFilename(_filename) {}
42
43void FileWriter::writeFile(Buffer filemap, uint32_t size) const {
44 size = std::min(size, filemap.getSize());
45#if defined(__unix__) || defined(__APPLE__)
46 size_t bytes_written = 0;
47 FILE* file;
48
49 file = fopen(mFilename, "wb");
50 if (file == nullptr)
51 ThrowFIE("Could not open file.");
52
53 bytes_written =
54 fwrite(filemap.begin(), 1, size != 0 ? size : filemap.getSize(), file);
55 fclose(file);
56 if (size != bytes_written) {
57 ThrowFIE("Could not write file.");
58 }
59
60#else // __unix__
61 auto wFileName = widenFileName(mFilename);
62 HANDLE file_h; // File handle
63 file_h =
64 CreateFileW(wFileName.data(), GENERIC_WRITE, FILE_SHARE_WRITE, nullptr,
65 CREATE_ALWAYS, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
66 if (file_h == INVALID_HANDLE_VALUE) {
67 ThrowFIE("Could not open file.");
68 }
69
70 DWORD bytes_written;
71 if (!WriteFile(file_h, filemap.begin(), size ? size : filemap.getSize(),
72 &bytes_written, nullptr)) {
73 CloseHandle(file_h);
74 ThrowFIE("Could not read file.");
75 }
76 CloseHandle(file_h);
77
78#endif // __unix__
79}
80
81} // namespace rawspeed
#define ThrowFIE(...)
const uint8_t * begin() const
Definition Buffer.h:99
size_type RAWSPEED_READONLY getSize() const
Definition Buffer.h:115
const char * mFilename
Definition FileWriter.h:38
FileWriter(const char *filename)
void writeFile(Buffer fileMap, uint32_t size=0) const
std::wstring widenFileName(const char *fileName)
Definition FileIO.h:35