Qt:如何 lock/prevent 文件在写入时不被读取?

Qt: How to lock/prevent a file from being read while it is written?

我在 Windows 7.
上使用 Qt5 在我当前的项目中,我打开一个二进制文件,以便用来自 TCP 套接字的数据填充它。 通常,在填充文件后,我将其关闭,另一个应用程序将读取此二进制文件以进行进一步处理。
好吧,问题是:写入操作大约需要 4-5 秒(甚至更多)所以我需要找到一种方法 来防止其他应用程序在文件完全填充之前从二进制文件中读取 ...
下面是代码(但我想它不会有太大帮助):

int error = 0;
unsigned long dataLength;
char dataBuffer[1500];
QFile localFile("datafile.bin");
//
localFile.open(QIODevice::WriteOnly);
while(error == 0)
{
    error = readSocket(dataBuffer, &dataLength);
    if(error == 0)
    {
        localFile.write(dataBuffer, dataLength);
    }
    else
    {
        error = -1;
    }
}
localFile.close();

我正在考虑使用一个临时文件,在写入操作完成后重命名。
但也许还有另一个 better/smarter 想法?某种“锁定文件以供读取”也许...?

如果您拥有这两个应用程序的源代码,那么写入文件的一个应用程序可以通过许多 IPC 机制(例如本地套接字)之一向另一个应用程序发出信号,表明它已完成写入。

或者,写入具有不同文件名的文件,然后在写入完成后将文件重命名/复制到读取应用程序预期的位置。

但是,写出文件时建议使用QSaveFile,而不是QFile。正如文档所述:-

While writing, the contents will be written to a temporary file, and if no error happened, commit() will move it to the final file

所以这可能会为您解决问题。

我知道也许有点晚了,但我最近发现了一个 有趣的 解决方案,即一个名为 "Locked File":

的组件

The QtLockedFile class extends QFile with advisory locking functions.

This class extends the QFile class with inter-process file locking capabilities. If an application requires that several processes should access the same file, QtLockedFile can be used to easily ensure that only one process at a time is writing to the file, and that no process is writing to it while others are reading it.

class QtLockedFile : public QFile
{
public:
    enum LockMode { NoLock = 0, ReadLock, WriteLock };

    QtLockedFile();
    QtLockedFile(const QString &name);
    ~QtLockedFile();

    bool open(OpenMode mode);

    bool lock(LockMode mode, bool block = true);
    bool unlock();
    bool isLocked() const;
    LockMode lockMode() const;

private:
    LockMode m_lock_mode;
};

此 link 会将您带到正确的位置,其中 QLockedFile class 实现是:
https://github.com/kbinani/qt-solutions/tree/master/qtlockedfile

** 所以,我决定分享这个信息,也许其他 Qt 用户有兴趣! **