替换文本文件中的一行 [英] Replace a line in text file
本文介绍了替换文本文件中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想替换文件中的一行文本,但我不知道这个函数。
I want replace a line of text in a file, but I don't know a functions to this.
我有这个:
ofstream outfile("text.txt");
ifstream infile("text.txt");
infile >> replace whit other text;
任何答案?
未命中,在文件中的某一行中添加文本...
I miss to say, for add text in Some line in the file...
示例
infile.add(text, line);
C ++有这样的功能吗?
Does C++ have functions for this?
推荐答案
恐怕你可能需要重写整个文件。以下是您可以做到的:
I'm afraid you'll probably have to rewrite the entire file. Here is how you could do it:
#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。
Just uncomment the commented lines if you only want it to replace the first occurance. Also, I forgot, in the end add code that deletes filein.txt and renames fileout.txt to filein.txt.
这篇关于替换文本文件中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文