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

I think this should be pretty simple, but my google search has not helped so far ... I need to write an existing file in C ++, but not necessarily at the end of the file.

I know that when I just want to add text to my file, I can pass the ios:app flag when I call open in my stream object. However, this allows me to write only at the very end of the file, but not in the middle of it.

I made a short program to illustrate the problem:

 #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(); } 
+8
c ++ fstream ifstream ofstream
source share
2 answers

You cannot insert the middle of a file. You must copy the old file to the new file and paste everything you want in the middle while copying to the new file.

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

+12
source share

You can write to the end and swap lines until they are in the correct position. Here is what I had to do. Here is the test.txt file before:

 12345678 12345678 12345678 12345678 12345678 

Here is a sample of my program

 #include <iostream> #include <fstream> #include <string> using namespace std; fstream& goToLine(fstream& file, int line){ int charInLine = 10; //number of characters in each line + 2 //this file has 8 characters per line int pos = (line-1)*charInLine; file.seekg(pos); file.seekp(pos); return file; } fstream& swapLines(fstream& file, int firstLine, int secondLine){ string firstStr, secondStr; goToLine(file,firstLine); getline(file,firstStr); goToLine(file,secondLine); getline(file,secondStr); goToLine(file,firstLine); file.write(secondStr.c_str(),8); //Make sure there are 8 chars per line goToLine(file,secondLine); file.write(firstStr.c_str(),8); return file; } int main(){ fstream file; int numLines = 5; //number of lines in the file //open file once to write to the end file.open("test.txt",ios::app); if(file.is_open()){ file<<"someText\n"; //Write your line to the end of the file. file.close(); } //open file again without the ios::app flag file.open("test.txt"); if(file.is_open()){ for(int i=numLines+1;i>3;i--){ //Move someText\n to line 3 swapLines(file,i-1,i); } file.close(); } return 0; } 

Here is the test.txt file after:

 12345678 12345678 someText 12345678 12345678 12345678 

Hope this helps!

+1
source share

All Articles