Delete a QTemporaryFile which is in use by a different app

  • I wrote an application which displays the file contents of a custom archive in a QTreeView.
    The user can then double click a file to open it in a default application.

    I extract the file into a QTemporaryFile and run QDesktopServices::openUrl(QUrl(tempfile->fileName())) to open it.
    The problem is, when the application is closed while the temporary file is still open by the default application, it doesn't get deleted (tempfile->remove() returns false).

    Is there a way to force delete the file or is there maybe a better way doing this?

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QDesktopServices>
    #include <QUrl>
    #include <QDebug>
    #include <QByteArray>
    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)
        m_tempFile = new QTemporaryFile("tempXXXXXX.mp3", this);
        QFile testFile("your_song.mp3");;
        QByteArray fileData(testFile.readAll());
        QDataStream out(m_tempFile);
        qDebug()<<"Opening "<< m_tempFile->fileName();
        //is opned (in my case) by VLC
        // if app is closed tempXXXXXX.mp3 doesn't get deleted
            qDebug()<<"Couldn't delete "<< m_tempFile->fileName();
        delete m_tempFile;
        delete ui;

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Are you using Windows ? Depending on how the file is opened, you can't delete it.

  • @SGaist Yes, I am using Windows. Is there maybe a way to mark the files for deletion on reboot? So they at least get removed later.

  • @ProgSys said:

    Is there maybe a way to mark the files for deletion on reboot? So they at least get removed later.

    AFAIK there is no such way,
    The best you can do - ask user if he wants to stop using file and delete it or maintain a list of remained to be deleted files and check it on next start-up and ask if user want to delete them.

  • @alex_malyu Ok, I guess I'll just pop up some error messages.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.