I won't store the content of file into memory, it will consume much memory. I wonder if there is any tricks or other
API to solve my issue?
Absolutely. Use MMFs (memory mapped files) instead and open the file in a way that gives your process exclusive
access.
See:
CreateFileMapping,
MapViewOfFileEx,
FlushViewOfFile,
UnmapViewOfFile
I reckon the set of
API names does not necessarily give away how useful it is. You intend not to keep all of it in memory, fine. Go MMF. MMFs will allow you to map only a portion and even then this view is backed by the file itself. Consider it something like the principle of the page file, just inverse. But the best is that you can treat the mapped view as though it was a buffer in memory. The memory manager of Windows will take care that it gets paged back in whenever you
access a page that has been paged out (i.e. is/was backed by the file you created the mapping of).
But may I ask why exactly - or rather what for - you need the locking? If you just want to prevent other processes from touching the file(s), why not open it exclusively with
CreateFile with only
FILE_SHARE_READ or even 0? Shouldn't that resolve your issue (even without MMF)? This will allow any other processes to open the file, but only for reading. So your process would be the only one able to
write to the file using that particular
handle (subsequent handles will have the same limitations, no matter whether inside your process or another one).