在文本文件中间附加字符串

Appending string in the middle of a text file

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

这是我的代码

#include <string>
#include <iostream>
#include <fstream>
int main(void){
    fstream myfile2;
    myfile2.open("test2.txt", ios::app);
    string checkline;
    getline(myfile2, checkline);
    int razmer=checkline.length();
    string balli="256";
    myfile2.seekp(razmer);
    myfile2<<balli;
}

test2.txt由2个字符串组成,所以它看起来像

Ivanov
Petrov

我想从Ivanov到> Ivanov 256。不碰第二根弦。但是我的代码根本不能工作。

编辑文本文件并不容易。通常的解决方案是将整个源文件读入内存,在内存中进行修改,然后将所有文件写出来。

在您的示例中,文件似乎是基于行的,您可以逐行读取它并将行放在std::vector中。编辑要编辑的行,然后循环遍历vector并写出这些行。

注意:当写入文件时,您以写模式打开它,因此文件将被重新创建并丢失所有旧内容。