Important: Please read the Qt Code of Conduct -

The proper way to close a QFile?

  • QFile example_file('/usr/test/file.txt');
    if( | QFile::Text) {
        QString line = example_file.readLine();
        qDebug() << "line:" << line;
    example_file.flush(); // redundant?
    example_file.close(); // is this needed if I flush or does flush take care of memory leaks already?

    How do I close a file I open in with QFile? Does flush take care of memory leaks or is it useless to use flush when I will use 'close' directly after anyways?

  • Do you understand that flushing the file isn't relevant when reading? Flush doesn't have anything to do with memory leaks.

    But to your direct question:
    See the documentation for the destructor QFile::~QFile() It implicitly closes the file if it is open. Since your object is local (stack allocated) the destructor will automatically be executed when the object goes out of scope.

  • @legitnameyo
    Although what @Kent-Dorfman says about stack-allocated destructor auto-closing is quite correct, I would always put in an explicit close() as soon as I am finished with any file, personally. It's good practice, especially for potential future code changes. You never need flush() on read, and you don't need flush() on write if it's immediately followed by close().

Log in to reply