diff --git a/tiny_gltf.h b/tiny_gltf.h index 23b16c9..b626835 100644 --- a/tiny_gltf.h +++ b/tiny_gltf.h @@ -2207,6 +2207,15 @@ bool WriteImageData(const std::string *basepath, const std::string *filename, void TinyGLTF::SetFsCallbacks(FsCallbacks callbacks) { fs = callbacks; } +#ifdef _WIN32 +static inline std::wstring UTF8ToWchar(const std::string &str) { + int wstr_size = MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), nullptr, 0); + std::wstring wstr(wstr_size, 0); + MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), &wstr[0], (int)wstr.size()); + return wstr; +} +#endif + #ifndef TINYGLTF_NO_FS // Default implementations of filesystem functions @@ -2227,7 +2236,7 @@ bool FileExists(const std::string &abs_filename, void *) { #else #ifdef _WIN32 FILE *fp; - errno_t err = fopen_s(&fp, abs_filename.c_str(), "rb"); + errno_t err = _wfopen_s(&fp, UTF8ToWchar(abs_filename).c_str(), L"rb"); if (err != 0) { return false; } @@ -2321,8 +2330,12 @@ bool ReadWholeFile(std::vector *out, std::string *err, } return false; } +#else +#ifdef _WIN32 + std::ifstream f(UTF8ToWchar(filepath).c_str(), std::ifstream::binary); #else std::ifstream f(filepath.c_str(), std::ifstream::binary); +#endif if (!f) { if (err) { (*err) += "File open error : " + filepath + "\n"; @@ -2358,7 +2371,11 @@ bool ReadWholeFile(std::vector *out, std::string *err, bool WriteWholeFile(std::string *err, const std::string &filepath, const std::vector &contents, void *) { +#ifdef _WIN32 + std::ofstream f(UTF8ToWchar(filepath).c_str(), std::ofstream::binary); +#else std::ofstream f(filepath.c_str(), std::ofstream::binary); +#endif if (!f) { if (err) { (*err) += "File open error for writing : " + filepath + "\n"; @@ -5631,7 +5648,11 @@ static void SerializeGltfBufferData(const std::vector &data, static bool SerializeGltfBufferData(const std::vector &data, const std::string &binFilename) { +#ifdef _WIN32 + std::ofstream output(UTF8ToWchar(binFilename).c_str(), std::ofstream::binary); +#else std::ofstream output(binFilename.c_str(), std::ofstream::binary); +#endif if (!output.is_open()) return false; output.write(reinterpret_cast(&data[0]), std::streamsize(data.size())); @@ -6489,7 +6510,11 @@ static bool WriteGltfStream(std::ostream &stream, const std::string &content) { static bool WriteGltfFile(const std::string &output, const std::string &content) { +#ifdef _WIN32 + std::ofstream gltfFile(UTF8ToWchar(output).c_str()); +#else std::ofstream gltfFile(output.c_str()); +#endif if (!gltfFile.is_open()) return false; return WriteGltfStream(gltfFile, content); } @@ -6526,7 +6551,11 @@ static void WriteBinaryGltfStream(std::ostream &stream, static void WriteBinaryGltfFile(const std::string &output, const std::string &content) { +#ifdef _WIN32 + std::ofstream gltfFile(UTF8ToWchar(output).c_str(), std::ios::binary); +#else std::ofstream gltfFile(output.c_str(), std::ios::binary); +#endif WriteBinaryGltfStream(gltfFile, content); }