Solved 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) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_tempFile = new QTemporaryFile("tempXXXXXX.mp3", this); m_tempFile->setAutoRemove(true); m_tempFile->open(); QFile testFile("your_song.mp3"); testFile.open(QIODevice::ReadOnly); QByteArray fileData(testFile.readAll()); QDataStream out(m_tempFile); out<<fileData; m_tempFile->close(); qDebug()<<"Opening "<< m_tempFile->fileName(); //is opned (in my case) by VLC QDesktopServices::openUrl(QUrl("file:///"+m_tempFile->fileName())); } MainWindow::~MainWindow() { // if app is closed tempXXXXXX.mp3 doesn't get deleted if(!m_tempFile->remove()) qDebug()<<"Couldn't delete "<< m_tempFile->fileName(); delete m_tempFile; delete ui; }
-
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.