1 /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * This file is part of openfx-supportext <https://github.com/devernay/openfx-supportext>,
4 * Copyright (C) 2013-2018 INRIA
5 *
6 * openfx-supportext is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * openfx-supportext 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
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with openfx-supportext. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
18 * ***** END LICENSE BLOCK ***** */
19
20 /*
21 * OFX utiliy functions to open a file safely with UTF-8 encoded strings.
22 */
23
24 #include "ofxsFileOpen.h"
25
26 #if defined(_WIN32)
27 #include <windows.h>
28 #include <fcntl.h>
29 #include <sys/stat.h>
30 #endif
31
32 using std::string;
33 using std::wstring;
34
35
36 namespace OFX {
37 #ifdef _WIN32
38 std::wstring
utf8_to_utf16(const string & str)39 utf8_to_utf16 (const string& str)
40 {
41 wstring native;
42
43 native.resize( MultiByteToWideChar (CP_UTF8, 0, str.data(), (int)str.length(), NULL, 0) );
44 MultiByteToWideChar ( CP_UTF8, 0, str.data(), (int)str.length(), &native[0], (int)native.size() );
45
46 return native;
47 }
48
49 string
utf16_to_utf8(const wstring & str)50 utf16_to_utf8 (const wstring& str)
51 {
52 string utf8;
53
54 utf8.resize( WideCharToMultiByte (CP_UTF8, 0, str.data(), (int)str.length(), NULL, 0, NULL, NULL) );
55 WideCharToMultiByte (CP_UTF8, 0, str.data(), (int)str.length(), &utf8[0], (int)utf8.size(), NULL, NULL);
56
57 return utf8;
58 }
59
60 #endif
61
62 std::FILE*
fopen_utf8(const char * path_utf8,const char * mode)63 fopen_utf8(const char* path_utf8,
64 const char* mode)
65 {
66 #ifdef _WIN32
67 // on Windows fopen does not accept UTF-8 paths, so we convert to wide char
68 wstring wpath = utf8_to_utf16 (path_utf8);
69 wstring wmode = utf8_to_utf16 (mode);
70
71 return ::_wfopen ( wpath.c_str(), wmode.c_str() );
72 #else
73
74 // on Unix platforms passing in UTF-8 works
75 return std::fopen (path_utf8, mode);
76 #endif
77 }
78 } // namespace OFX
79