問題描述
您不會想像使用 C++ 標準庫為 Windows 應用程序打開文件這樣基本的事情是棘手的......但它似乎是.這里的 Unicode 是指 UTF-8,但我可以轉換為 UTF-16 或其他格式,重點是從 Unicode 文件名中獲取一個 ofstream 實例.在我修改自己的解決方案之前,這里有首選路線嗎?尤其是跨平臺的?
You wouldn't imagine something as basic as opening a file using the C++ standard library for a Windows application was tricky ... but it appears to be. By Unicode here I mean UTF-8, but I can convert to UTF-16 or whatever, the point is getting an ofstream instance from a Unicode filename. Before I hack up my own solution, is there a preferred route here ? Especially a cross-platform one ?
推薦答案
C++ 標準庫不支持 Unicode.char
和 wchar_t
不需要是 Unicode 編碼.
The C++ standard library is not Unicode-aware. char
and wchar_t
are not required to be Unicode encodings.
在 Windows 上,wchar_t
是 UTF-16,但標準庫中沒有直接支持 UTF-8 文件名(char
數據類型在 Windows 上不是 Unicode)
On Windows, wchar_t
is UTF-16, but there's no direct support for UTF-8 filenames in the standard library (the char
datatype is not Unicode on Windows)
使用 MSVC(以及 Microsoft STL),提供了一個文件流構造函數,它采用 const wchar_t*
文件名,允許您將流創建為:
With MSVC (and thus the Microsoft STL), a constructor for filestreams is provided which takes a const wchar_t*
filename, allowing you to create the stream as:
wchar_t const name[] = L"filename.txt";
std::fstream file(name);
但是,C++11 標準并未指定此重載(它僅保證基于 char
的版本的存在).從版本 g++ 4.8.x 開始,它也沒有出現在替代 STL 實現中,例如 GCC 的 libstdc++ for MinGW(-w64).
However, this overload is not specified by the C++11 standard (it only guarantees the presence of the char
based version). It is also not present on alternative STL implementations like GCC's libstdc++ for MinGW(-w64), as of version g++ 4.8.x.
請注意,就像 Windows 上的 char
不是 UTF8,在其他操作系統上 wchar_t
可能不是 UTF16.所以總的來說,這不太可能是便攜的.根據標準未定義給定 wchar_t
文件名的流,并且在 char
s 中指定文件名可能很困難,因為 char 使用的編碼因操作系統而異
Note that just like char
on Windows is not UTF8, on other OS'es wchar_t
may not be UTF16. So overall, this isn't likely to be portable. Opening a stream given a wchar_t
filename isn't defined according to the standard, and specifying the filename in char
s may be difficult because the encoding used by char varies between OS'es.
這篇關于如何使用 unicode 文件名打開 std::fstream(ofstream 或 ifstream)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!