我想替换文件中的一行文本,但我不知道它的功能.
我有这个:
ofstream outfile("text.txt"); ifstream infile("text.txt"); infile >> replace whit other text;
对此有何答案?
例
infile.add(text,line);
C有这个功能吗?
解决方法@H_403_18@
我担心你可能不得不重写整个文件.您可以这样做:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string strReplace = "HELLO";
string strNew = "GOODBYE";
ifstream filein("filein.txt"); //File to read from
ofstream fileout("fileout.txt"); //Temporary file
if(!filein || !fileout)
{
cout << "Error opening files!" << endl;
return 1;
}
string strTemp;
//bool found = false;
while(filein >> strTemp)
{
if(strTemp == strReplace){
strTemp = strNew;
//found = true;
}
strTemp += "\n";
fileout << strTemp;
//if(found) break;
}
return 0;
}
输入文件:
ONE
TWO
THREE
HELLO
SEVEN
ONE
TWO
THREE
GOODBYE
SEVEN
如果您只希望它替换第一次出现,请取消注释注释行.另外,我忘了,最后添加删除filein.txt的代码并将fileout.txt重命名为filein.txt.
#include <iostream> #include <fstream> using namespace std; int main() { string strReplace = "HELLO"; string strNew = "GOODBYE"; ifstream filein("filein.txt"); //File to read from ofstream fileout("fileout.txt"); //Temporary file if(!filein || !fileout) { cout << "Error opening files!" << endl; return 1; } string strTemp; //bool found = false; while(filein >> strTemp) { if(strTemp == strReplace){ strTemp = strNew; //found = true; } strTemp += "\n"; fileout << strTemp; //if(found) break; } return 0; }
输入文件:
ONE TWO THREE HELLO SEVEN
ONE TWO THREE GOODBYE SEVEN
如果您只希望它替换第一次出现,请取消注释注释行.另外,我忘了,最后添加删除filein.txt的代码并将fileout.txt重命名为filein.txt.