tags:

views:

700

answers:

2

I have a program writing/reading from a file, and I want to lock the file for other instances of my application. How can I do it (in c++ visual studio 2003)? I tried using the _locking() but then also I myself cannot reach the file when trying to read/write (in the same instance). I know there's an option of LockFile() but have no idea how to set it properly. Please help me.

+5  A: 

You can simply use the Win32 API CreateFile and then specify no sharing rights. This will ensure that no other processes can access the file.

The dwShareMode DWORD specifies the type of sharing you would like, for example GENERIC_READ. If you specify 0 then that means no sharing rights should be granted.

Example:

HANDLE hFile = CreateFile(_T("c:\\file.txt"), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);


If you want to only lock a certain part of the file you can use LockFile or LockFileEx.

Example:

 //Lock the first 1024 bytes
 BOOL bLocked = LockFile(hFile, 0, 0, 1024, 0);


For locking on other platforms please see my post here.

Brian R. Bondy
A: 

You want LockFileEx() (exclusive file locking). Have a look at this discussion from Secure Programming Cookbook for C and C++.

Shane C. Mason