Qt - Repeatedly write at beginning of file

942 views Asked by At

How do I write a new line to the beginning of a QTextstream?

I am tracing a binary tree backwards and writing the result to a log-file. I want the root-node to be the first line on the list. Simply appending lines leads to a reverse order. What I need to do is to add the new line at the top of the file.

Here is a simplified example of what I have got:

QFile mFile("fileName.csv");
QTextStream out(&mFile);
if (!mFile.open(QFile::WriteOnly | QFile::Text)){
        qDebug() << " Could not open foundPath file";
        return;
}

int cursor = 10;
while (cursor > 0){
    out << cursor << "\n";
    cursor--;
}

The result is obviously 10, 9, ... , 1, but I want 1, 2, ..., 10.

1

There are 1 answers

1
Marcus Müller On

You can't overwrite the "first line", because files aren't stored line-wise, but as bytes after bytes; there's nothing special about a line break. So if you replace the first line of a file by a line that's longer, you will overwrite parts of the second line, for example.

You could read in the whole file, and prepend the first line before re-writing the rest, but that is going to be very slow and ressource intense once your log file gets bigger.

The right approach would obviously be to reverse the display, not the log.