jaa2013
jaa2013

Reputation: 241

c++ transfer file line by line in reverse order

I have this code that is supposed to transfer a file into another file in reverse order, line by line. However it does not work. Maybe I forgot to add something:

while(cnvFile.good()) {
    getline(cnvFile, cnvPerLine);

    reverseFile << cnvPerLine;
    reverseFile.seekp(0, ios::beg);
}

Upvotes: 0

Views: 653

Answers (1)

Cornstalks
Cornstalks

Reputation: 38238

When you seek to the beginning and try to write, you're not inserting data, you're overwriting data. A simple (albeit probably far from optimal) solution would be something like:

std::string reversedContents
while (getline(inFile, line)) {
    // This actually *appends* to the beginning, not overwriting
    reversedContents = line + "\n" + reversedContents; // manually add line breaks back in
}

// now write reversedContents to a file...

Upvotes: 1

Related Questions