Open file exclusively/lock file

Viewed 3477

I want to lock an existing file to prevent usage (read and write) from another process. That is, any subsequent attempt to open the file by this process or any other process should fail with an 'access denied' error.

The CreateFile WINAPI function has a dwShareMode parameter which does exactly that, I'm looking for similar functionality while still being able to use QFile.

2 Answers

One way I found is to use LockFile on the underlying OS handle after you have already opened your file.

Note that LockFile has a slightly different behavior - subsequent attempts to open succeed, but actual reading or writing will fail with ERROR_LOCK_VIOLATION.

#include <windows.h>
#include <io.h>
bool lockFile(QFile *file) {
    return (bool) LockFile((HANDLE) _get_osfhandle(file->handle()), 0, 0, -1, -1);
}
void test() {
    QFile f("test.txt");
    f.open(QIODevice::ReadOnly);
    lockFile(&f);
}
Related