1. 以二进制方式打开文件,写入BOM头
FILE* pFile = nullptr;
_wfopen_s(&pFile, szLogFilePath, L"wb");
// UTF-16 LE BOM : FFFE
unsigned char bom[] = { 0xFF, 0xFE };
if (pFile)
{
fwrite(bom, sizeof(unsigned char), sizeof(bom), pFile);
fclose(pFile);
}
2. 以Unicode方式打开文件,写入内容
FILE* pFile = nullptr;
wchar_t name[] = L"中國哲學書電子化計劃";
_wfopen_s(&pFile, L"C:\\TEMP\\ChineseLetters.txt", L"a,ccs=UNICODE");
if (pFile)
{
fwrite(name, sizeof(wchar_t), sizeof(name), pFile);
fclose(pFile);
}
参考资料
- c-text-file-wont-save-in-unicode-it-keeps-saving-in-ansi
- fopen-s-wfopen-s
- 如何判断一个文本文件的编码