C++ Fstream to replace specific line?

2019-08-11 18:12发布

问题:

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.