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
.
Right-click on the file. In the menu that appears, select Lock File. To unlock, right-click the file and select Unlock File.
Procedure. In the administrative console, click Servers > Server Types > WebSphere application servers > server_name > [Container Settings] Container Services > Transaction Service. Clear the Enable file locking check box. Click Apply or OK.
An exclusive or write lock gives a process exclusive access for writing to the specified part of the file. While a write lock is in place, no other process can lock that part of the file. A shared or read lock prohibits any other process from requesting a write lock on the specified part of the file.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With