lib/io: Add a replacement for fopen() which works on Windows

fopen() does not correctly handle non-ASCII paths on Windows.
This commit is contained in:
Povilas Kanapickas 2021-11-01 02:52:48 +02:00
parent 089b8e4749
commit cf732aba37
2 changed files with 15 additions and 0 deletions

View File

@ -54,4 +54,16 @@ void open_utf8_path(std::fstream& stream, const std::string& path, std::ios_base
open_utf8_path_impl(stream, path, mode); open_utf8_path_impl(stream, path, mode);
} }
std::FILE* fopen_utf8_path(const std::string& path, const std::string& mode)
{
#if SYSAPI_WIN32
auto wchar_path = utf8_to_win_char(path);
auto wchar_mode = utf8_to_win_char(mode);
return _wfopen(reinterpret_cast<wchar_t*>(wchar_path.data()),
reinterpret_cast<wchar_t*>(wchar_mode.data()));
#else
return std::fopen(path.c_str(), mode.c_str());
#endif
}
} // namespace barrier } // namespace barrier

View File

@ -18,6 +18,7 @@
#ifndef BARRIER_LIB_IO_FSTREAM_H #ifndef BARRIER_LIB_IO_FSTREAM_H
#define BARRIER_LIB_IO_FSTREAM_H #define BARRIER_LIB_IO_FSTREAM_H
#include <cstdio>
#include <iosfwd> #include <iosfwd>
#include <ios> #include <ios>
@ -30,6 +31,8 @@ void open_utf8_path(std::ofstream& stream, const std::string& path,
void open_utf8_path(std::fstream& stream, const std::string& path, void open_utf8_path(std::fstream& stream, const std::string& path,
std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out); std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out);
std::FILE* fopen_utf8_path(const std::string& path, const std::string& mode);
} // namespace barrier } // namespace barrier
#endif #endif