James
James

Reputation: 783

How to open a file and lock it in C?

If I open a file using the following code:

FILE *file = fopen("D:\\1.mp4", "rb");

This will not lock the file, so for example I can open this file using Notepad and write to it!

So is there a way I can make sure that no other application is allowed to write to this file, or should I use WinAPI to accomplish this?

Upvotes: 1

Views: 557

Answers (2)

Amit
Amit

Reputation: 46323

In C, there apparently isn't a way to do this, although POSIX has some ways to do that. Look here for details.

In WINAPI, it's rather simple to do with CreateFile (but you end up with a Windows Handle, not a FILE pointer):

HANDLE hFile = CreateFile("D:\\1.mp4", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);

Upvotes: 3

Joni
Joni

Reputation: 111279

The windows feature you want to use is the "sharing mode." You can set it using the _fsopen function. To deny write access use _SH_DENYWR as the third parameter.

Upvotes: 4

Related Questions