1

Using Qt, I am opening a file for read-write access, first reading some content, then seeking back in the stream and writing some new data. When I close the file, I'd like to truncate it at the current file position. Currently, I do it with a f.resize(f.pos()) and wonder whether there is a simpler way to achieve this:

QFile f(filename);
if(f.open(QFile::ReadWrite)) {
    QTextStream str(&f);

    // do some reading from str here

    f.reset();

    // write some stuff to str here

    f.resize(f.pos());
} else
    qDebug() << "Could not open file" << it->filename();
f.close();

Using Qt::Truncate already truncates the file before reading, which is not what I want.

user52366
  • 1,035
  • 1
  • 10
  • 21
  • 3
    *wonder whether there is a simpler way to achieve this* - simpler than one line of code to call `resize`? – TheDarkKnight Dec 09 '16 at 10:09
  • 1
    Would it not be slightly more "correct" to truncate the file immediately after the seek, before you start writing? That way (1) you don't have to worry about the file being closed without the truncation happening, and (2) if something goes wrong (e.g. app crashes during the write), you don't have "ghost" data. – Allison Lock Dec 09 '16 at 10:39
  • 1
    That is a good point, this would indeed be safer. I was somehow hoping that there would be an option to truncate the file automatically at pos() upon closing. – user52366 Feb 17 '17 at 13:06

0 Answers0