且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

替换文本文件中的一行

更新时间:2023-02-23 17:16:40

恐怕你可能需要重写整个文件。以下是您可以做到的:

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.