在一个C++项目中,我想要打开一个文件(
fstream::open()
)(这似乎是一个主要问题)。我的程序在Windows构建时失败了。
File "ä" (UTF-8 0xC3 0xA4)
std::string s = ...; //Convert s std::fstream f; f.open(s.c_str(), std::ios::binary | std::ios::in); //Works (f.is_open() == true) f.close(); f.open(s.c_str(), std::ios::binary | std::ios::in | std::ios::out); //Doesn't work
The string
s
is UTF-8 encoded, but then converted from UTF-8 to Latin1 (0xE4). I'm using Qt, soQString::fromUtf8(s.c_str()).toLocal8Bit().constData()
.Why can I open the file for reading, but not for writing?
File "и" (UTF-8 0xD0 0xB8)
Same code, doesn't work at all.
似乎这个字符不适用于Windows-1252字符集。我该如何打开这样的fstream(我没有使用MSVC,因此没有 fstream :: open(const wchar_t *,ios_base :: openmode)
)?
_wfopen
等)通过其长名称访问文件。或者,您可以使用短名称。 - Kerrek SB_wfopen
。如果你使用的是不同的C运行时库(比如Cygwin GCC的libc),那么你就要看这个运行时库的Unicode支持了。 - Adam RosenfieldCreateFileW
)。如果它们不支持,您就需要直接调用CreateFileW
。 - Philippstd::wfstream
类,但它的open
方法也只接受文件名的const char*
。如果您想要能够打开Unicode文件名,则需要使用C的stdio库,或者完全缓冲文件数据将其全部读入内存,并使用std::stringstream
来解析数据。 - Adam Rosenfield