Help in editing a file
Nov 4, 2012 at 12:09am UTC
Hello all,
i am trying to edit a specific line of a file, without using another file.
i am trying to read the data at n'th line and process data and then write back the results at the same line.
Only problem i am facing is, when i am trying to write data, other lines are being affected too, because of change in processed data length.
Any suggestions?
INPUT
1
22
333
4444
5
6
7
8
9
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <fstream>
#include <limits>
#include<iostream>
using namespace std;
std::fstream& GotoLine(std::fstream& file, unsigned int num){
file.seekg(std::ios::beg);
for (unsigned int i=0; i < num - 1; ++i){
file.ignore(std::numeric_limits<std::streamsize>::max(),'\n' );
}
return file;
}
std::fstream& GotoLineWrite(std::fstream& file, unsigned int num){
file.seekg(std::ios::beg);
for (unsigned int i=0; i < num - 1; ++i){
file.ignore(std::numeric_limits<std::streamsize>::max(),'\n' );
}
long len=0;
len=file.tellg();
file.seekp(len,std::ios::beg);
return file;
}
int main(){
using namespace std;
fstream file("bla.txt" ,ios::in|ios::out);
GotoLine(file, 4);
int line=0;
file >> line;
cout<<line<<endl;
line=line+14;
GotoLineWrite(file,5);
file<<line;
cout<<line;
return 0;
}
OUTPUT
EXPECTED OUTPUT
1
22
333
4444
4458
6
7
8
9
0
Last edited on Nov 4, 2012 at 1:05am UTC
Topic archived. No new replies allowed.