-1

I'm currently having troubles with my program. I wanna modify only 6 lines in a text files located from line 76 to 81 and I don't know how to do it.

I want to add something at the very end of these lines(or replace'em if it's easier) and not modify any of the other lines(maybe check if the modification hasn't already occurred too but that's bonus).

I found myself lost looking for an answer on google, may you help me ?

Voltra Neo
  • 85
  • 1
  • 7
  • I highly recommend using a plain text editor. You should make the file read & writable before editing it. – Thomas Matthews Jul 01 '16 at 21:31
  • _"may you help me ?"_ Probably not. There are so many possible solutions for your problem, that your question isn't asking abput particular problem. – πάντα ῥεῖ Jul 01 '16 at 21:31
  • You can simply add the line number at the beginning of each line. So when you read it, you can check for the first item's value to be >=76 and <=81, and modify the lines if the condition is satisfied... –  Jul 02 '16 at 02:11

1 Answers1

0

If your replacement text is the same, exact length as the original text, you can open the file as read/write and overwrite the text.

The traditional method (since reel-to-reel tapes), has been to copy the text that is not modified to a new file, then the modified text, then the remainder of the original text.

I recommend using std::getline and std::string.

If you really need performance, you may want consider double buffering.

Edit 1: example

for (unsigned int i = 0; i < 76; ++i)
{
  std::string text;
  std::getline(original_file, text);
  new_file << text << "\n";
}
// Write new text to new file
// Read old text and ignore it.
// Copy remaining text to new file.

Background
Although files can be treated as random access (meaning you can seek to a random position), the text is not of fixed length. In general, text files can be considered as containing variable length records of text. The only way to count a line is to read until a newline is found. So in order to seek to line 76, one has to count line endings until 76 is found.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154