c++ - 在以读/写/追加模式打开文件后,我可以检测到文件的预先存在吗?

标签 c++ qt boost qfile

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

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

最佳答案

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

但是,我记得防止文件 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 安装之外)我有一个更新的安装用于私有(private)摆弄。

因此,我制作了一个小样本来验证这一点:

#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。)

关于c++ - 在以读/写/追加模式打开文件后,我可以检测到文件的预先存在吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54221827/

相关文章:

c++ - timespec 初始化时非阻塞 TCP 套接字挂起 (C++)

c++ - 水平对齐动态创建的小部件 qt c++

qt - 如何在 PyQt4 中显示 QDialog 时执行回调?

c++ - perl 正则表达式比 c++/boost 更快

c++ - Boost http 服务器示例不起作用?

c++ - 使用单个索引访问子矩阵的有效方法

c++ - 模板库中的名称查找 : why do we add this->

c++ - 使用 Boost::spirit 编写的解析器的性能问题

C++ 识别运算符 = 的不同

c++ - 我的线程仍然卡住我的 GUI