c++ - wfstream 不写

标签 c++ unicode g++

我有以下 C++ 代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
    wstring ws1 = L"Infinity: \u2210";
    wstring ws2 = L"Euro: €";

    wchar_t w[] = L"Sterling Pound: £";

    wfstream out("/tmp/unicode.txt");
    out.write(ws1.c_str(), ws1.size());
    out << ws1 << endl << ws2 << endl << w << endl;
    out.flush();
    out.close();
}

程序编译没有问题,但文件永远不会打开,更不用说写入了。此外,如果我使用 std::wcout 我仍然没有得到正确的输出,只有 ? 用于无穷大和磅符号。

我的系统是 g++ 4.4.3,运行 ubuntu linux 10.4 64 位。

最佳答案

标准中没有关于将多宽字符流转换为字符设备的定义,您需要对您的系统进行试验以了解发生了什么。通常通过 C 设置本地应该适用于 std 输入/输出流 std::cin/std::cout。

setlocale("");  // Loads the local that the machine is configured for (see you config)
                // If it is not configured it default to the "C" locale

文件流对象可能不会自动检索本地,因此有时值得显式设置流的本地。

std::locale   defaultLocale(""); // from machine config
std::wfstream out;
out.imbue(defaultLocale);        // imbue must be done before opening
                                 // otherwise it is ignored.

out.open("/tmp/unicode.txt");

让我们做一些测试以确保您确实在编写:

if (!out)
{
    std::cout << "Failed to open file\n";
}

作为旁注:

out.write(ws1.c_str(), ws1.size()); // size() is the number of characters (wide)
                                    // write is expecting the number of bytes.

另一个注意事项:

out.flush();    // flush() happens automatically when the file is closed
out.close();    // close() happens automatically when the stream is destroyed.
                // So technically it is better not to use these
                // as they are specific to file streams which will prevent you from
                // easily replacing this with a generic stream

关于c++ - wfstream 不写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3857390/

相关文章:

c++ - 函数传递映射中的异常错误

c++ - 这个按升序打印按行和按列排序的矩阵的程序的零在哪里?

Grails 未正确编码 unicode 字符

gcc - g++ 4.1.2 与 g++ 4.6 混合

c++ - MinGW 链接路径

C++ list<T>::iterator 不能在派生类模板中使用

c++ - C++ 中的单一错误

c++ - 在 Qt 中使用多个 Ui 和 Ui 类?

c++ - Visual Studio 2017 中的 UTF-8 支持 std::experimental::filesystem::path

php - PHP 中的 preg_match 和 UTF-8