How to fix bug in file writing operation

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <fstream>
#include <limits>
#include<iostream>
#include<string.h>
using namespace std;

//Filling file to skip copying whole file into memory
void make_file(fstream& file)
{
	char *a= new char[100];
	memset(a,'*',99);
	int i=100;
	while(i--)
	{
		file<<a<<endl;
	}

}

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-1,std::ios::beg);
    return file;
}


int main(){
    using namespace std;
    fstream file("bla.txt",ios::in|ios::out);
    make_file(file);
    GotoLine(file, 2); // This Function takes you to line number 2 to read input
    string line="";
    getline(file,line);
    cout<<line<<endl;
    line="+Changed";
    GotoLineWrite(file,2); //// This Function takes you to line number 2 to write data. This not working for <=5
    file<<line;
    cout<<line;
    return 0;
}



Hello all,

I wrote this code to read, write and edit in file. I basically initially filled file with characters which are replaced by later data.

Everything is going fine if i choose line number >=5.
But magically i don't know whats happening when i choose to edit line number <=5.
Can you please look into the code and help me a bit.
Its too important for me.

Thank you.
Topic archived. No new replies allowed.