最近遇到了須要大量修改txt文件中指定內容的狀況,嘗試過fgets()、fwrite()和WriteString()、ReadString()兩種搭配使用的方法。
ios
可是因爲每使用一次前面提到的4個方法的其中之一,指針就會自動指向下一行,使得寫入時原文件排版發生改變。
spa
並且由於txt文件體積較大的緣由,使用一次將所有文檔讀取到內存中而後再在內存中對其進行修改,勢必會消耗大量的內存,這不是任何一我的所指望的。
指針
最後採用了中間文件的方法解決上述問題。
code
#include <iostream> #include <fstream> #include <ostream> #include <cstdlib> #include <string> using namespace std; CString strFileName, strTempFile; strTempFile.Format("%s\\Temp.txt", m_tszAppFolder); //臨時文件路徑 strFileName.Format("%s\\Data.txt", m_tszAppFolder); //源文件路徑 string strLine; //從源文件讀取,修改字符串,並將字符串寫到臨時文件 fstream FileSrc(strFileName); ofstream FileOut(strTempFile, ios::out|ios::trunc); while(!FileSrc.eof()) { getline(FileSrc, strLine); //這裏添加對字符串進行修改的代碼 FileOut << strLine << endl; } FileSrc.close(); FileOut.close(); //將臨時文件中的數據會讀到指定文件中 fstream FileSrc_1(strTempFile); ofstream FileOut_1(strFileName, ios::out|ios::trunc); while(!FileSrc_1.eof()) { getline(FileSrc_1, strLine); FileOut_1 << strLine << endl; } FileSrc_1.close(); FileOut_1.close(); //最後刪除臨時文件 DeleteFile(strTempFile);