2

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?
}
lolwut123
  • 33
  • 1
  • 5

2 Answers2

6

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.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • hi sir, how can i upvote this i modified this and it works. thank you! :) today i learned how to use seekp. – lolwut123 Sep 02 '12 at 20:51
  • by the way why are we using -line.size() i don't understand – lolwut123 Sep 02 '12 at 20:53
  • Well, it is necessary to move backward. A positive value would move forward relative to the current position, a negative value moves backward. Actually, the code incorrectly assumes that `std::string::size_type` is a signed type which is not the case (it should still work, though): please use `-std::ios::off_type(line.size())` instead of `-line.size()`. – Dietmar Kühl Sep 02 '12 at 21:09
  • hmm wait now its just appending it to the the string before it? :S – lolwut123 Sep 02 '12 at 21:32
  • The seek should get it to the start of the line and writing the character should overwrite the character. There is a potential issue if your files are terminated with CR/LF sequences: in this case you might need to seek one more character (and to make things portable you probably want to open the file adding `std::ios_base::binary` to the open mode to suppress folding the CR/LF sequence into an LF on some systems). – Dietmar Kühl Sep 02 '12 at 23:00
1

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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165