替换文本文件中的一行

War*_*ock 7 c++ stream ifstream

我想替换文件中的一行文本,但我不知道它的功能.

我有这个:

ofstream outfile("text.txt");
ifstream infile("text.txt");

infile >> replace whit other text;
Run Code Online (Sandbox Code Playgroud)

对此有何答案?

我想念,在文件的某些行添加文字...

infile.add(text, line); 
Run Code Online (Sandbox Code Playgroud)

C++是否具有此功能?

Ant*_*ton 9

我担心你可能不得不重写整个文件.您可以这样做:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输入文件:

ONE
TWO
THREE
HELLO
SEVEN
Run Code Online (Sandbox Code Playgroud)

输出文件:

ONE
TWO
THREE
GOODBYE
SEVEN
Run Code Online (Sandbox Code Playgroud)

如果您只希望它替换第一次出现,请取消注释注释行.另外,我忘了,最后添加删除filein.txt的代码并将fileout.txt重命名为filein.txt.

  • 您可以通过替换`strTemp + ="\n"避免潜在的分配(并保存一行); fileout << strTemp;`with`fileout << strTemp <<'\n';`. (2认同)

Kas*_*yap 3

您需要在文件中查找正确的行/字符/位置,然后覆盖。没有这样的搜索和替换功能(据我所知)。

  • 如果替换文本的字节大小与其替换的文本大小不完全相同,则此方法将不起作用。 (12认同)