最近遇到了须要大量修改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);