fstream :: open()Unicode或Non-Ascii字符在Windows上不起作用(使用std :: ios :: out) [英] fstream::open() Unicode or Non-Ascii characters don't work (with std::ios::out) on Windows

查看:152
本文介绍了fstream :: open()Unicode或Non-Ascii字符在Windows上不起作用(使用std :: ios :: out)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++项目中,我想打开一个文件(fstream::open())(这似乎是一个主要问题).我的程序的Windows版本严重失败.

In a C++ project, I want to open a file (fstream::open()) (which seems to be a major problem). The Windows build of my program fails miserably.

  • 文件ä"(UTF-8 0xC3 0xA4)

  • 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

字符串s是UTF-8编码的,但随后从UTF-8转换为Latin1(0xE4).我正在使用Qt,所以QString::fromUtf8(s.c_str()).toLocal8Bit().constData().

The string s is UTF-8 encoded, but then converted from UTF-8 to Latin1 (0xE4). I'm using Qt, so QString::fromUtf8(s.c_str()).toLocal8Bit().constData().

为什么我可以打开文件进行读取,但不能打开?

Why can I open the file for reading, but not for writing?

文件и"(UTF-8 0xD0 0xB8)

File "и" (UTF-8 0xD0 0xB8)

相同的代码完全无效.

似乎此字符不适合Windows-1252字符集.如何打开这样的fstream(我没有使用MSVC,所以没有fstream::open(const wchar_t*, ios_base::openmode) )?

It seems, this character doesn't fit in the Windows-1252 charset. How can I open such an fstream (I'm not using MSVC, so no fstream::open(const wchar_t*, ios_base::openmode))?

推荐答案

在Windows上使用标准API(例如std :: fstream),如果文件名可以使用当前设置的"ANSI代码页"进行编码,则只能打开文件"(CP_ACP).

Using the standard APIs (such as std::fstream) on Windows you can only open a file if the filename can be encoded using the currently set "ANSI Codepage" (CP_ACP).

这意味着可能存在在Windows上使用这些API无法完全打开的文件.除非Microsoft支持将CP_ACP设置为CP_UTF8,否则不能使用Microsoft的CRT或C ++标准库实现.

This means that there can be files which simply cannot be opened using these APIs on Windows. Unless Microsoft implements support for setting CP_ACP to CP_UTF8 then this cannot be using Microsoft's CRT or C++ standard library implementation.

(Windows具有一个名为短"文件名的功能,启用该功能后,驱动器上的每个文件都具有一个可通过标准API使用的ASCII文件名.但是,此功能已不复存在,因此并不代表可行的解决方案. )

(Windows has had a feature called "short" filenames where, when enabled, every file on the drive had an ASCII filename that can be used via standard APIs. However this feature is going away so it does not represent a viable solution.)

这篇关于fstream :: open()Unicode或Non-Ascii字符在Windows上不起作用(使用std :: ios :: out)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆