更换文件中的行C

Replace line in file C++

本文关键字:文件      更新时间:2023-10-16

我正在尝试替换line in file

示例

aaa bbb ccc
bbb ccc ddd
ccc ddd eee

我想用

之类的替换第二行
111 222 333

因此结果将为

aaa bbb ccc
111 222 333
ccc ddd eee

我尝试了

while (getline(infile, curline))
{
    if (counter == line)
    {
        outfile << input1 << "t" << input2 << "t" << input3 << "t" << input4 << endl;
        break;
    }
    counter++;
}

其中 line 是我要替换的行数。

感谢您的帮助!

文件不是"硬盘上的内存"。因此,如果您打算更改文件,则必须创建具有更改内容的新文件,然后将其重命名为旧文件的名称(当然,删除了旧文件(。因此,尝试将代码修改为类似的内容:

while (getline(infile, curline))
{
    if (counter == line)
    {
        // altered line creation
        outfile << input1 << "t" << input2 << "t" << input3 << "t" << input4 << endl;
    }
    else
    {
        // the line goes without changes
        outfile << curline << endl;
        counter++;
    }
}