7

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.

sashoalm
  • 75,001
  • 122
  • 434
  • 781
fpdragon
  • 1,867
  • 4
  • 25
  • 36

2 Answers2

2

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);
}
sashoalm
  • 75,001
  • 122
  • 434
  • 781
1

Have you tried saving (overwriting) with Notepad++? I believe the correct behavior is that it wont let you write to the same filename. Opening (reading) is not enforceable; writing is the real test.

Preet Kukreti
  • 8,417
  • 28
  • 36
  • 1
    On windows it is possible to give an exclusive lock to a file and prevent reading and writing. The question is how to do this with qt? I do need to lock the file from getting read. – fpdragon Aug 10 '12 at 08:20