简体   繁体   English

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

[英]Appending string in the middle of a text file

here is my code 这是我的代码

#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 consists of 2 strings, so it is looks like test2.txt由2个字符串组成,因此看起来像

Ivanov
Petrov

I want to make from Ivanov -> Ivanov 256 . 我想从Ivanov > Ivanov 256 With no touching 2nd string. 没有感人的第二弦。 But my code did not work at all. 但是我的代码根本不起作用。 Thanks in advance. 提前致谢。

There's no easy way to edit a text file. 没有简单的方法可以编辑文本文件。 The usual solution is to read the whole source file into memory, make your modifications in memory, and then write out all of the file. 通常的解决方案是将整个源文件读入内存,在内存中进行修改,然后写出所有文件。

In your example where the file seems to be line-based, you could read it line by line and put the lines in a std::vector . 在您的文件似乎是基于行的示例中,您可以逐行读取文件并将其放入std::vector Edit the line you want to edit, then loop over the vector and write out the lines. 编辑要编辑的行,然后在向量上循环并写出这些行。

Note: When writing the file, you open it in write mode, so the file is recreated and looses all old contents. 注意:写入文件时,您以写入模式打开它,因此将重新创建文件并释放所有旧内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM