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

MFC CString 讀取文件內容寫入另一文件:常見錯誤與正確寫法

     編輯:程式設計綜合問答

問題代碼分析

CFile f(_T("D:\\11\\0.txt"), CFile::modeCreate | CFile::modeWrite | CFile::modeNoTruncate);
f.SeekToEnd();
CString a = _T("D:\\11\\0.txt ") + str; // 錯誤:拼接的是檔案路徑而非內容
f.Write(a, a.GetLength() * sizeof(TCHAR));

開發者誤以為 str 會自動寫入,實際上將「目標檔案路徑」與內容拼接後寫入,導致檔案內容錯誤。

正確做法

CFile f(_T("D:\\11\\0.txt"), CFile::modeCreate | CFile::modeWrite | CFile::modeNoTruncate);
f.SeekToEnd();
f.Write(str, str.GetLength() * sizeof(TCHAR)); // 直接寫入讀取到的字串內容
f.Close();

若需在內容前加入分隔符或換行,請對 str 進行字串操作後再寫入。

補充提示

  • 使用 CFile::modeNoTruncate 確保不清空原有內容。
  • SeekToEnd() 定位至檔案末尾實現追加。
  • 寫入長度以 sizeof(TCHAR) 計算,支援 Unicode/ANSI 專案。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved