Windows是否允许同时写入文件

Does Windows allow simultaenous writing to a file?

本文关键字:文件 许同时 是否 Windows      更新时间:2023-10-16

我使用Qt创建了一个c++程序,它可以写入文件。这个程序可能会有多个实例,每个实例都通过本地网络访问文件。

我使用QFile::ReadWrite作为我的文件打开选项。如果一个进程以这种模式打开文件,我发现另一个进程也可以打开它进行写入。我使用file.write(text)写入文件。如果两个过程同时尝试这样做,会发生什么?Windows能处理这个问题吗?

我想知道是否需要使用Window的CreateFile(...)重新实现,并使用0作为共享模式?

谢谢。

Qt是开源的,所以只需查看内部(qfsfleengine_win.cpp):

bool QFSFileEnginePrivate::nativeOpen(QIODevice::OpenMode openMode)
{
...
// All files are opened in share mode (both read and write).
DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
...
 // Create the file handle.
fileHandle = CreateFile((const wchar_t*)fileEntry.nativeFilePath().utf16(),
                        accessRights,
                        shareMode,
                        &securityAtts,
                        creationDisp,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);

因此,除了"不在乎"之外,Qt不提供任何文件共享功能。