1

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?

James
  • 703
  • 8
  • 17

2 Answers2

4

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.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • That's a great answer, but it's neither standard C, nor is it winapi. It's "the best of both worlds" while not being either of them :-) – Amit Jul 01 '15 at 07:34
3

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);
Community
  • 1
  • 1
Amit
  • 45,440
  • 9
  • 78
  • 110
  • Shouldn't the function parameters be like this: `HANDLE hFile = CreateFile("D:\\1.mp4", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);`? – James Jul 01 '15 at 07:28
  • 2
    Note you can use `_open_osfhandle` followed by `_fdopen` to obtain a `FILE*` from a `HANDLE`. – Jonathan Potter Jul 01 '15 at 07:41
  • @JonathanPotter you're right, but it's easier to use `_fsopen` as noted by Joni. The same "problem" remains though, this is not standard C and no longer standard WINAPI (such that could be transported to non C domain) – Amit Jul 01 '15 at 07:53