Ryan12345
Ryan12345

Reputation: 35

C++ Write on a Specific Line in a File

Right now I am able to read a specific line of a file, but the question is, how can I write on that same specific line in the file? For example, lets say line 1 says "Test", line 2 says "Congratz", Line 3 "Yay", how can I make it where I can replace like 2 with "Yess", or something in the form. Btw the way, in my int main() code, I call readLine(0); and to check if the lines zero, I call if (lineNumber == 0); Thanks in advance!

void readLine(int lineNum) {
    ifstream fin("StartupMap.dat");
    string s;
    long length;

    fin.seekg (0, ios::beg); // go to the first line

    for (int i = 0; i <= lineNumber; i++) // loop 'till the desired line
        getline(fin, s);
    if (lineNumber == 0)
        true1 = true;

    length = fin.tellg(); // tell the first position at the line, maybe +1 or -1. try if it's not working
    fin.seekg(length);

    lineNumber = lineNum;
}

Upvotes: 0

Views: 5759

Answers (1)

Galik
Galik

Reputation: 48605

A file is just a stream of characters. That means if you want to make a line longer then you have to shift everything in the file that appears after that line forwards to make room. Conversely if you want to make a line shorter you have to shift everything in the file after that line backwards.

It is incredibly inefficient.

The only practical way to avoid that in place is to make sure that all the lines are of fixed length.

Otherwise you either need to read in the whole file and write it out again after editing or else copy your file to a new file, changing it as you go.

For example:

3 lines in a file might look like this:

Test\nCongratz\nYay
0     5         14   <- start position of line

Line 1 is "Test"
Line 2 is "Congratz"
Line 3 is "Yay"

If you want to change line 2 to say "Yess" you need to move the 3rd line backwards:

Test\nYess\nYay <= now line 3 starts sooner
0     5     10  <- start position of line

That means shifting almost the entire file depending on where the edit is.

Upvotes: 3

Related Questions