• 5965阅读
  • 1回复

QT中如何用共享模式打开一个文件 [复制链接]

上一主题 下一主题
离线dd970512
 
只看楼主 倒序阅读 楼主  发表于: 2010-03-03
就像window下:
CFile f;
if(!f.Open(lpszFile,CFile::modeRead|CFile::shareDenyNone)) // CFile::shareDenyNone代表 Opens the file without denying other processes read or write access to the file,也就是打开文件,但不拒绝其它进程序读写这个文件。
[ 此帖被dd970512在2010-03-03 09:38重新编辑 ]
离线reback
只看该作者 1楼 发表于: 2010-03-04
bool QFSFileEnginePrivate::nativeOpen(QIODevice::OpenMode openMode)
{
    Q_Q(QFSFileEngine);

    // All files are opened in share mode (both read and write).
    DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;

    int accessRights = 0;
    if (openMode & QIODevice::ReadOnly)
        accessRights |= GENERIC_READ;
    if (openMode & QIODevice::WriteOnly)
        accessRights |= GENERIC_WRITE;

    SECURITY_ATTRIBUTES securityAtts = { sizeof(SECURITY_ATTRIBUTES), NULL, FALSE };

    // WriteOnly can create files, ReadOnly cannot.
    DWORD creationDisp = (openMode & QIODevice::WriteOnly)
                         ? OPEN_ALWAYS : OPEN_EXISTING;

    // Create the file handle.
    QT_WA({
        fileHandle = CreateFileW((TCHAR *)nativeFilePath.constData(),
                                 accessRights,
                                 shareMode,
                                 &securityAtts,
                                 creationDisp,
                                 FILE_ATTRIBUTE_NORMAL,
                                 NULL);
    }, {
        fileHandle = CreateFileA(nativeFilePath.constData(),
                                 accessRights,
                                 shareMode,
                                 &securityAtts,
                                 creationDisp,
                                 FILE_ATTRIBUTE_NORMAL,
                                 NULL);
    });

    // Bail out on error.
    if (fileHandle == INVALID_HANDLE_VALUE) {
        q->setError(QFile::OpenError, qt_error_string());
        return false;
    }

    // Truncate the file after successfully opening it if Truncate is passed.
    if (openMode & QIODevice::Truncate)
        q->setSize(0);

    return true;
}

源代码,默认就是共享打开的,而且。。。只能共享打开
快速回复
限100 字节
 
上一个 下一个