在 read/write/append 模式下打开文件后,我可以检测到文件的预先存在吗?

Can I detect the pre-existance of a QFile after opening it in read/write/append mode?

我想用随机选择的文件名将一些文本写入文件,但希望要求该文件尚不存在。在简单的 QFile::exists 检查后跟带有检查名称的 open 之间存在竞争条件。

当我使用 QFile 打开文件时,确保该文件不是预先存在的最佳方法是什么?在使用 boost::filesystem::create_directory 时, 目录 也能很好地工作,因为它 returns 是一个布尔值,指示目录是否预先存在。但我看不到它如何处理文件。

我必须承认我从未亲自尝试过。

不过,我记得在文件 I/O 中防止竞争条件的常用方法是尝试分别处理可能的错误情况。

因此,我查看了 QFile::open() 它提供的内容并发现:

QIODevice::NewOnly:

Fail if the file to be opened already exists. Create and open the file only if it does not exist. There is a guarantee from the operating system that you are the only one creating and opening the file. Note that this mode implies WriteOnly, and combining it with ReadWrite is allowed. This flag currently only affects QFile. Other classes might use this flag in the future, but until then using this flag with any classes other than QFile may result in undefined behavior. (since Qt 5.11)


我刚刚意识到(除了我们高效的 Qt 5.9 安装之外)我安装了一个更新的用于私人摆弄。

因此,我做了一个小样本来检查一下:

#include <QtWidgets>

int main()
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  for (int i = 1; i <= 2; ++i) {
    qDebug() << "Iteration" << i;
    QFile qFile("test.txt");
    if (!qFile.open(QIODevice::WriteOnly | QIODevice::NewOnly)) {
      qDebug() << "qFile.open failed! Error code" << qFile.error();
    }
    qFile.write("test");
    qFile.close();
  }
  return 0;
}

输出:

Qt Version: 5.11.2
Iteration 1
Iteration 2
qFile.open failed! Error code 5
QIODevice::write (QFile, "test.txt"): device not open

我仍然不太确定如何发现它完全由于已经存在的文件而失败(而不是由于任何其他原因)。对我来说是肯定的,但一般来说?

(错误代码5就是QFileDevice::OpenError。)