gpt4 book ai didi

c++ - 编写 UTF-8 BOM 时出现异常

转载 作者:搜寻专家 更新时间:2023-10-31 02:13:08 26 4
gpt4 key购买 nike

我必须手动将 UTF-8 BOM 添加到一个简单的文本文件中。但是,我无法使用以下方法编写 BOM。凭借我相当有限的 C++ 知识,我实际上不明白我做错了什么。我认为这一定与我只写了 3 个字节的事实有关——而且无论出于何种原因,系统都希望我写 2 的倍数。该代码以 Unicode 字符集编译。欢迎任何指向我正确方向的提示。

FILE* fStream;
errno_t e = _tfopen_s(&fStream, strExportFile, TEXT("wt,ccs=UTF-8")); //UTF-8

if (e != 0)
{
//Error Handling
return 0;
}

CStdioFile* fileo = new CStdioFile(fStream);
fileo->SeekToBegin();

//Write BOM
unsigned char bom[] = { 0xEF,0xBB,0xBF };
fileo->Write(bom,3);
fileo->Flush(); //BOOM: Assertion failed buffer_size % 2 == 0

最佳答案

根据 Microsoft's documentation for _tfopen_s (强调):

When a Unicode stream-I/O function operates in text mode (the default), the source or destination stream is assumed to be a sequence of multibyte characters. Therefore, the Unicode stream-input functions convert multibyte characters to wide characters (as if by a call to the mbtowc function). For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters (as if by a call to the wctomb function).

您需要将 UTF-16 字符写入文件,然后文件将被翻译。您需要编写单个 16 位 0xfeff,而不是 3 字节序列 0xEF,0xBB,0xBF

关于c++ - 编写 UTF-8 BOM 时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41811368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com