Is there is a standard C/C++ function to check if a file is used by another process before opening it?
-
7Nope. – Rapptz Jul 23 '13 at 00:44
-
2That sounds like operating-system-specific behaviour. – Carl Norum Jul 23 '13 at 00:44
-
I think you should add the platform you interested to know about. – Ran Eldan Jul 23 '13 at 00:45
-
1See [How to check if a file has been opened by another application in C++](http://stackoverflow.com/questions/1048592/how-to-check-if-a-file-has-been-opened-by-another-application-in-c) question. – Shobhit Puri Jul 23 '13 at 00:45
-
@Carl, Windows 64 bits. – user987654 Jul 23 '13 at 00:56
-
1There is not. But there are several standard ways to check if this question has been asked before. – Sebastian Mach Jul 23 '13 at 09:37
3 Answers
If we turn this around a little and say how do you give only one process access to a file or may be many processes sharing write access to a file without problem. Then I would recommend looking at these:

- 8,768
- 4
- 37
- 72
One way to ensure that a file is exclusively opened by only one process is to attempt to create a lock file, usually with a .LCK extension.
E.g. if the filename is foo, then attempt to create foo.LCK. If it succeeds, write the pid of the process in the foo.LCK file so that you can delete the LCK file later if the process for some reason doesn't delete it when it no longer needs the lock.
Once a .LCK file has been created, all other attempts to create it will fail.
Another way to do is by using flock().
In both cases, the locking is advisory and not mandatory. I.e. a non-cooperating process is free to do what it wants.

- 1,574
- 8
- 5
If you try to open a file with
fopen();
and it returns an error, then the following is possible:
- File does not exist
OR
- File is being used by another process.

- 876
- 1
- 9
- 19