Mihran Hovsepyan
Mihran Hovsepyan

Reputation: 11108

How lock a file in windows using c++?

How can I lock a file in windows to only current thread (no other threads from same process and no other processes) can access (read/write) the file?

If it is possible please tell me some fcntl-like solution (solution which locks file having its descriptor). But in any case other solutions are welcome too.

Upvotes: 3

Views: 7611

Answers (2)

Chad
Chad

Reputation: 19052

In Windows, you can open a file with exclusive access with the API function CreateFile and specifying 0 as the share mode. More details at this MSDN link, and this MSDN link.

Upvotes: 5

Scott Chamberlain
Scott Chamberlain

Reputation: 127603

Use the WinAPI call LockFile, Here is a example of its use. However this will only protect you from other processes from touching your file, it still lets other threads in the same process use the file.

EDIT: I did not see this was C++ sorry, I only know the inter thread c# solution, however that MSDN link can at least get you started on preventing other processes from touching your file.

Upvotes: 1

Related Questions