如何打开一个std :: fstream(ofstream或ifstream)与unicode文件名? [英] How to open an std::fstream (ofstream or ifstream) with a unicode filename?
问题描述
你不会想象一些基本的东西,如使用C ++标准库为Windows应用程序打开一个文件是棘手的...但似乎是。通过Unicode这里我的意思是UTF-8,但我可以转换为UTF-16或任何,点是从Unicode文件名得到一个流实例。在我解决自己的解决方案之前,有没有首选的路线?特别是跨平台的?
C ++标准库不支持Unicode。 char
和 wchar_t
不需要是Unicode编码。
在Windows上, wchar_t
是UTF-16,但是没有直接支持标准库中的UTF-8文件名( char
datatype在Windows上不是Unicode)
对于MSVC(因此是Microsoft STL),提供了filestreams的构造函数, > const wchar_t * filename,可以创建流:
wchar_t const name [ = Lfilename.txt;
std :: fstream file(name);但是,这种重载不是由C ++ 11标准规定的(它只保证存在一个基于 char
的版本)。它也不存在于替代的STL实现,如GCC的libstdc ++对于MinGW(-w64),版本g ++ 4.8.x。
注意,就像 char
在Windows上不是UTF8,在其他操作系统 wchar_t
可能不是UTF16。所以总体来说,这不太可能是便携式的。打开一个给定 wchar_t
文件名的流不是根据标准定义的,并且在 char
中指定文件名困难,因为char使用的编码在OS之间变化。
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 ?
解决方案 The C++ standard library is not Unicode-aware. char
and wchar_t
are not required to be Unicode encodings.
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)
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);
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.
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.
这篇关于如何打开一个std :: fstream(ofstream或ifstream)与unicode文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!