简体   繁体   中英

Qt - Repeatedly write at beginning of file

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM