我可以使用ofstream来写UTF-8 BOM文件。我也可以使用wofstream将Unicode字符串写入文件,并使用utf8_locale(codecvt_utf8)进行缓冲。但是,我无法找到如何以UTF-8 BOM编码将Unicode字符串写入文件的方法。
BOM是文件开头的第一个可选字节,用于指定其编码方式。它与std::fstream
没有直接关系,因为fstream
只是用于读写随机字节/字符的文件流。
在继续编写您的UTF8编码字符串之前,您只需要手动写入BOM即可。
unsigned uint8_t utf8BOM[] = {0xEF,0xBB,0xBF};
fileStream.write(utf8BOM,sizeof(utf8BOM));
//write the rest of the utf8 encoded string..
U+FEFF
。 - Steve JessopFE FF
小端序:FF FE
- user2249683U+FEFF
。 - rubenvb#include <iostream>
#include <string>
#include <fstream>
#include <codecvt>
int main()
{
std::string utf8 = u8"日本医療政策機構\nPhở\n";
std::ofstream f("c:\\test\\ut8.txt");
unsigned char bom[] = { 0xEF,0xBB,0xBF };
f.write((char*)bom, sizeof(bom));
f << utf8;
return 0;
}
L
前缀),然后从UTF16转换为UTF8:#include <iostream>
#include <string>
#include <fstream>
#include <Windows.h>
std::string get_utf8(const std::wstring &wstr)
{
if (wstr.empty()) return std::string();
int sz = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), 0, 0, 0, 0);
std::string res(sz, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &res[0], sz, 0, 0);
return res;
}
std::wstring get_utf16(const std::string &str)
{
if (str.empty()) return std::wstring();
int sz = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), 0, 0);
std::wstring res(sz, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &res[0], sz);
return res;
}
int main()
{
std::string utf8 = get_utf8(L"日本医療政策機構\nPhở\n");
std::ofstream f("c:\\test\\ut8.txt");
unsigned char bom[] = { 0xEF,0xBB,0xBF };
f.write((char*)bom, sizeof(bom));
f << utf8;
return 0;
}
utf-8
不需要BOM
。 - axiac