C++ Fstream to replace specific line?

牧云@^-^@ 提交于 2019-12-24 17:01:48

问题


okay i'm stumped on how to do this. I managed to get to the line I want to replace but i don't know how to replace it.

say a file called file.txt containts this:

1
2
3
4
5

and I want to replace line 3 so that it says 4 instead of 3. How can I do this?

#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

fstream file;
string line;

int main(){
file.open("file.txt");
for(int i=0;i<2;i++){
getline(file,line);
}
getline(file,line);
//how can i replace?
}

回答1:


Assuming you have opened a file in read/write mode you can switch between reading and writing by seeking, including seeking to the current position. Note, however, that written characters overwrite the existing characters, i.e., the don't insert new characters. For example, this could look like this:

std::string line;
while (std::getline(file, line) && line != end) {
}
file. seekp(-std::ios::off_type(line.size()) - 1, std::ios_base::cur);
file << 'x';

Even if you are at the right location seeking is needed to put the stream into an unbound state. Trying to switch between reading and writing without seeking causes undefined behavior.




回答2:


The usual approach is to read from one file while writing to another. That way you can replace whatever you want, without having to worry about whether it's the same size as the data it's replacing.



来源:https://stackoverflow.com/questions/12239505/c-fstream-to-replace-specific-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!