Qt-删除文件

24

我需要删除一个特定的文件。 我已经尝试过这个:

msgBox.setButtonText(QMessageBox::Ok , tr("Ok"));
msgBox.setButtonText(QMessageBox::Cancel , tr("Cancel"));

int ret = msgBox.exec();

switch (ret)
{
    case QMessageBox::Ok:
    {
    #ifdef Q_OS_IOS
        QStringList paths = QStandardPaths::standardLocations(QStandardPaths::DataLocation);
        QString dbFile = paths.first().append("/log.dat");
    #else
        QString dbFile = "log.dat";
    #endif
        QSettings settings(CGlobalZone::m_companyName, CGlobalZone::m_softwareName);
        settings.clear();
        QDir dir;
        dir.remove(dbFile);

        break;

    case QMessageBox::Cancel:
        QTimer::singleShot(1500, this, SLOT(close()));
        break;
}


但是不幸的是dbFile仍然存在。我如何删除"dbFile"?


那么?有什么问题吗? - Greenflow
你是在Windows下工作吗? - Greenflow
@Greenflow 是的,我正在开发 Windows 版本。 - Farzan Najipour
1
请查看Farzan Njr的回答评论。路径可能不正确,或者您的文件仍然处于打开状态。在Windows下无法删除已打开的文件。 - Greenflow
2个回答

47

使用

    QFile file (dbFile);
    file.remove();

而不是

  QDir dir;
   dir.remove(dbFile);

dir.remove 应该可以工作。除非路径错误,或者他正在 Windows 下工作且文件仍然打开。 - Greenflow
我尝试使用QFileInfo,希望它们有一个通用的remove()方法,但是没有成功 :( - kayleeFrye_onDeck

24

在Qt中删除文件的更简短的解决方案可能是:

QFile::remove(dbFile);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接