首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 源文件編碼批量轉換:GBK 轉 UTF-8 (Visual Studio 專用工具)

     編輯:關於C++

背景

VS 默認保存為 GBK,但跨平台/現代編譯器偏好 UTF-8。手動另存為極其繁瑣,需批量轉換工具。

工具原理

  1. 遞歸掃描指定目錄下所有 .cpp、.h 文件。
  2. 讀取文件前 3 字節檢測 BOM:EF BB BF 表示已是 UTF-8,跳過。
  3. 調用 Windows API MultiByteToWideChar(CP_ACP...) 將 GBK 轉寬字符,再 WideCharToMultiByte(CP_UTF8...) 轉 UTF-8。
  4. 寫入文件時加上 UTF-8 BOM (EF BB BF)。

核心代碼 (MFC 控制台程序)

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

集成到 VS 構建流程

  1. 編譯生成 convert.exe。
  2. 專案屬性 → 構建事件 → 構建前事件命令行:
    $(ProjectDir)convert.exe $(ProjectDir)src
  3. 每次編譯前自動將 src 目錄下源文件轉為 UTF-8。

替代方案

  • Python 腳本:codecs.open + os.walk 更簡潔跨平台。
  • Notepad++ / VS Code 批量轉換編碼功能。
  • CMake file(READ/WRITE) + string(ENCODING) (CMake 3.18+)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved