Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to middle of a file in C++?

I think this should be quite simple, but my googling didn't help so far... I need to write to an existing file in C++, but not necessarily at the end of the file.

I know that when I just want to append text to my file, I can pass the flag ios:app when calling open on my stream object. However, this only let's me write to the very end of the file, but not into its middle.

I made a short program to illustrate the issue:

#include <iostream>
#include <fstream>

using namespace std;

int main () {

  string path = "../test.csv";

  fstream file;
  file.open(path); // ios::in and ios::out by default

  const int rows = 100;
  for (int i = 0; i < rows; i++) {
    file << i << "\n";
  }  

  string line;
  while (getline(file, line)) {
    cout << "line: " << line << endl; // here I would like to append more text to certain rows
  }


  file.close();

}
like image 636
nburk Avatar asked Jun 04 '15 11:06

nburk


1 Answers

You cannot insert in the middle of the file. You have to copy the old file to a new file and insert whatever you want in the middle during copying to the new file.

Otherwise, if you intend to overwrite data/lines in the existing file, that is possible by using std::ostream::seekp() to identify the position within the file.

like image 141
Steephen Avatar answered Oct 01 '22 16:10

Steephen