首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

MFC 專案(Unicode 字元集)讀取 UTF-8 文字檔並正確顯示的完整步驟

     編輯:程式設計綜合問答

核心問題

MFC Unicode 專案內部使用 UTF-16 (wchar_t/CString),直接讀取 UTF-8 檔案會導致中文亂碼。

解決方案:MultiByteToWideChar 轉換

CString ReadUtf8File(LPCTSTR filePath)
{
    CFile file;
    if (!file.Open(filePath, CFile::modeRead | CFile::typeBinary))
        return _T("");

    DWORD fileSize = (DWORD)file.GetLength();
    std::vector<BYTE> buffer(fileSize);
    file.Read(buffer.data(), fileSize);
    file.Close();

    // UTF-8 -> UTF-16
    int wlen = MultiByteToWideChar(CP_UTF8, 0, (LPCCH)buffer.data(), fileSize, NULL, 0);
    std::vector<wchar_t> wbuf(wlen);
    MultiByteToWideChar(CP_UTF8, 0, (LPCCH)buffer.data(), fileSize, wbuf.data(), wlen);

    return CString(wbuf.data(), wlen);
}

替代方案:CStdioFile + 手動轉碼

CStdioFile file;
file.Open(filePath, CFile::modeRead | CFile::typeBinary);
CStringA line;
CString content;
while (file.ReadString(line)) {
    int wlen = MultiByteToWideChar(CP_UTF8, 0, line, line.GetLength(), NULL, 0);
    CStringW wline;
    MultiByteToWideChar(CP_UTF8, 0, line, line.GetLength(), wline.GetBuffer(wlen), wlen);
    wline.ReleaseBuffer(wlen);
    content += wline + _T("\r\n");
}
file.Close();

注意事項

  • 檔案若含 BOM (EF BB BF),需手動略過前 3 bytes。
  • 大檔案建議分塊讀取轉換,避免記憶體壓力。
  • 寫入 UTF-8 時用 WideCharToMultiByte(CP_UTF8, ...)。

參考資源

Microsoft 官方討論串:MFC UTF-8 讀寫完整範例

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved