VS 默認保存為 GBK,但跨平台/現代編譯器偏好 UTF-8。手動另存為極其繁瑣,需批量轉換工具。
.cpp、.h 文件。EF BB BF 表示已是 UTF-8,跳過。MultiByteToWideChar(CP_ACP...) 將 GBK 轉寬字符,再 WideCharToMultiByte(CP_UTF8...) 轉 UTF-8。EF BB BF)。void convertGBToUTF8(CString path, const char* gbk) {
CFile fp(path, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
int len = MultiByteToWideChar(CP_ACP, 0, gbk, -1, NULL, 0);
wchar_t* w = new wchar_t[len+1];
MultiByteToWideChar(CP_ACP, 0, gbk, -1, w, len);
len = WideCharToMultiByte(CP_UTF8, 0, w, -1, NULL, 0, NULL, NULL);
char* utf8 = new char[len+1];
WideCharToMultiByte(CP_UTF8, 0, w, -1, utf8, len, NULL, NULL);
delete[] w;
unsigned char bom[3] = {0xEF,0xBB,0xBF};
fp.Write(bom, 3);
fp.Write(utf8, len);
delete[] utf8;
fp.Close();
}
void recursiveFile(CString pattern) {
CFileFind finder;
BOOL found = finder.FindFile(pattern);
while (found) {
found = finder.FindNextFile();
if (finder.IsDots()) continue;
CString p = finder.GetFilePath();
if (finder.IsDirectory()) {
recursiveFile(p + _T("\\*.*"));
} else if (p.Right(4)==_T(".cpp") || p.Right(2)==_T(".h")) {
// 讀取、檢測 BOM、轉換...
convertGBToUTF8(p, content);
}
}
}
convert.exe。$(ProjectDir)convert.exe $(ProjectDir)srcsrc 目錄下源文件轉為 UTF-8。codecs.open + os.walk 更簡潔跨平台。file(READ/WRITE) + string(ENCODING) (CMake 3.18+)。