使用 MFC 創建一個空的文本文件(`.txt`),支持 Unicode 內容寫入。
CString strPath = _T("E:\\Cache\\new.txt");
CString strText = _T("Hello, MFC!\r\n第二行內容");
// 1. 打開文件:modeCreate(不存在則創建) | modeWrite(寫入) | modeNoTruncate(可選,不截斷)
CFile file;
if (!file.Open(strPath, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary)) {
AfxMessageBox(_T("文件創建失敗"));
return;
}
// 2. 寫入 Unicode 簽名 (BOM: 0xFEFF),讓記事本正確識別編碼
WORD unicodeBOM = 0xFEFF;
file.Write(&unicodeBOM, sizeof(WORD));
// 3. 寫入字符串內容(寬字符)
file.Write(strText, strText.GetLength() * sizeof(TCHAR));
// 4. 關閉句柄
file.Close();
| 標誌/步驟 | 作用 | 注意事項 |
|---|---|---|
modeCreate | 文件不存在時創建 | 若文件存在則打開,指針在開頭 |
modeWrite | 寫入權限 | 需配合 modeRead 讀寫共享 |
typeBinary | 二進制模式 | 避免 `\n` 自動轉 `\r\n`,手動控制換行 |
| 寫入 BOM (0xFEFF) | 標識 UTF-16 LE 編碼 | 記事本/編輯器依賴 BOM 識別 Unicode |
sizeof(TCHAR) | Unicode 下為 2 字節 | 配合 GetLength() 計算字節數 |
CStdioFile file;
if (file.Open(strPath, CFile::modeCreate | CFile::modeWrite | CFile::typeText)) {
file.WriteString(_T("第一行\r\n")); // 自動處理換行、編碼(ANSI)
file.WriteString(strText);
file.Close();
}
typeText:文本模式,自動 `\n` ↔ `\r\n` 轉換,**但默認寫入 ANSI (MBCS)**,Unicode 項目下需配合 `CFile::typeBinary` 手動寫 BOM + 寬字符。