C++ 替换文本文件中的一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9505085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace a line in text file
提问by Warkanlock
I want replace a line of text in a file, but I don't know a functions to this.
我想替换文件中的一行文本,但我不知道它的功能。
I have this:
我有这个:
ofstream outfile("text.txt");
ifstream infile("text.txt");
infile >> replace whit other text;
Any answers for this?
对此有任何答案吗?
I miss to say, for add text in Some line in the file...
我想说的是,在文件的某些行中添加文本...
Example
例子
infile.add(text, line);
Does C++ have functions for this?
C++ 有这方面的功能吗?
回答by Anton
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;
}
Input-file:
输入文件:
ONE
TWO
THREE
HELLO
SEVEN
Output-file:
输出文件:
ONE
TWO
THREE
GOODBYE
SEVEN
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.
如果您只想替换第一次出现,只需取消注释注释行即可。另外,我忘了,最后添加删除 filein.txt 并将 fileout.txt 重命名为 filein.txt 的代码。
回答by Kashyap
回答by zwol
The only way to replace text in a file, or add lines in the middle of a file, is to rewrite the entire filefrom the point of the first modification. You cannot "make space" in the middle of a file for new lines.
替换文件中的文本或在文件中间添加行的唯一方法是从第一次修改的点开始重写整个文件。您不能在文件中间为新行“腾出空间”。
The reliableway to do this is to copy the file's contents to a new file, making the modifications as you go, and then use rename
to overwrite the old file with the new one.
执行此操作的可靠方法是将文件内容复制到新文件中,随时进行修改,然后使用rename
新文件覆盖旧文件。