以Unicode(UTF-16 LE)编码保存文本

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);
}

参考资料

  1. c-text-file-wont-save-in-unicode-it-keeps-saving-in-ansi
  2. fopen-s-wfopen-s
  3. 如何判断一个文本文件的编码
原文地址:https://www.cnblogs.com/lkpp/p/save_text_unicode.html