将unicode字符/字符串写入文件

问题描述 投票:0回答:2

我正在尝试使用std::wofstream将unicode字符写入文件,但putwrite函数不会写任何字符。

示例代码:

#include <fstream>
#include <iostream>

int main()
{
    std::wofstream file;
    file.open("output.txt", std::ios::app);
    if (file.is_open())
    {
        wchar_t test = L'й';
        const wchar_t* str = L"фывдлао";
        file.put(test);
        file.write(str, sizeof(str));
        file.close();
    }
    else
    {
        std::wcerr << L"Failed to open file" << std::endl;
    }

    std::cin.get();
    return 0;
}

output.txt文件为空,执行代码后没有写入wchar / string,为什么?我究竟做错了什么?

编辑:核心代码:

#include <fstream>
#include <iostream>

int main()
{
    std::wofstream file;
    file.open("output.txt", std::ios::app);
    if (file.is_open())
    {
        wchar_t test = L'й';
        const wchar_t* str = L"фывдлао";
        file.put(test);
        if (!file.good())
        {
            std::wcerr << L"Failed to write" << std::endl;
        }
        file.write(str, 8);
        file.close();
    }
    else
    {
        std::wcerr << L"Failed to open file" << std::endl;
    }

    std::cin.get();
    return 0;
}

在应用代码校正之后,我提出了Failed to write,但我仍然不明白我需要做什么来编写宽字符串和字符?

c++ file wchar wofstream
2个回答
2
投票

第一个问题立即发生:put无法写入宽字符,流将失败,但是你永远不会检查第一次写入是否成功:

file.put(test);
if(not file.good())
{
    std::wcerr << L"Failed to write" << std::endl;
}

第二个问题是sizeof(str)以字节为单位返回指针的大小,而不是以字节为单位返回字符串的大小。


1
投票

我用这种方式工作,不需要外部字符串库,如QString!

唯一使用std库和c ++ 11

#include <iostream>
#include <locale>
#include <codecvt>
#include <fstream>
#include <Windows.h>

int main()
{
    std::wofstream file;
    // locale object is responsible of deleting codecvt facet!
    std::locale loc(std::locale(), new std::codecvt_utf16<wchar_t> converter);

    file.imbue(loc);
    file.open("output.txt"); // open file as UTF16!

    if (file.is_open())
    {
        wchar_t BOM = static_cast<wchar_t>(0xFEFF);
        wchar_t test_char = L'й';
        const wchar_t* test_str = L"фывдлао";

        file.put(BOM);
        file.put(test_char);
        file.write(test_str, lstrlen(test_str));

        if (!file.good())
        {
            std::wcerr << TEXT("Failed to write") << std::endl;
        }

        file.close();
    }
    else
    {
        std::wcerr << TEXT("Failed to open file") << std::endl;
    }

    std::wcout << TEXT("Done!") << std::endl;

    std::cin.get();
    return 0;
}

文件输出:

yfıvdlao

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.