1

I am working on file locking for first time, and couldn't find relevant posts for solution in Google.

I am locking a file using this code, to lock file.

ifile = CreateFileW(FileName, GENERIC_READ |  GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);

In next line I am trying to open the same file using

errno_t ErrorNumber = _wfopen_s(FileHandle, FileName, "rb");

The purpose is to lock the file to prevent any other process from writing to it, while this function is reading its contents. I am getting EACCESS : 13 error code when opening the file with "rb".

Any ideas why and how to enable reading the file after locking it ?

Thanks Sujatha

EdChum
  • 376,765
  • 198
  • 813
  • 562
swtsvn
  • 11
  • 1
  • Out of curiosity, if the purpose of opening the file as you are is to *prevent* writing to it, any particular reason you're granting `FILE_SHARE_WRITE` and `FILE_SHARE_DELETE` (the arguably most-volatile of all writes) ? And is `FileHandle` **really** a `FILE**`, and if so, what does it point to (I can only hope a valid `FILE*`, but without code its impossible to say). – WhozCraig Sep 12 '14 at 09:28
  • possible duplicate of [Lock a file using windows c++ LockFIle() then get a stream from it?](http://stackoverflow.com/questions/24664046/lock-a-file-using-windows-c-lockfile-then-get-a-stream-from-it) – Harry Johnston Sep 12 '14 at 23:37

1 Answers1

0

To create a "lock file" on Win32 that won't allow other processes to open it:

ifile = CreateFileW(FileName, GENERIC_READ |  GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_FLAG_DELETE_ON_CLOSE, NULL);

CREATE_NEW and 0 for the sharing mode ensures that the file will only be opened by your process and FILE_FLAG_DELETE_ON_CLOSE ensures that it'll be auto-deleted when you close the file or your process (heaven forbid) crashes.

This is a somewhat clumsy way of achieving cross-process locks on Win32 though. Shared Mutex's were invented to solve this problem.

Andy Brown
  • 11,766
  • 2
  • 42
  • 61