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!
Chad
source share