If you have to "defend" against your own processes or "well behaved" processes, then you want to use flock
:
fp = fopen(fileName, fileMode);
if (fp != NULL) {
flock(fileno(fp), LOCK_EX);
...
fclose(fp); fp = NULL;
}
But those locks are advisory only, that is, any other process can choose to ignore them. Or not bother checking. I've just tried creating a file, opening it and locking with LOCK_EX, then sleeping for 60 seconds. During that time, another process was free to do whatever it wanted to the file (Linux, Ubuntu 18.04-LTS).
But if you need mandatory locking, that's not something that is available on all platforms since the kernel has to cooperate. Here you will find a description and example on how the limited mandatory lock support in Linux can be used.
On the other hand, in Windows this is automatic:
Windows defaults to automatic, mandatory file locking. UNIXes default to manual,
cooperative file locking. In both cases, the defaults can be overridden, but in both
cases they usually aren’t. (source).
A workaround can be to temporarily rename the file being worked on to a unique name, possibly creating an empty file with the old name in its place, then renaming it back once you've done; or copying the file as above, leaving a copy for other programs to read. Write denial can also be achieved by changing the file permissions. These solutions require to handle some edge cases, e.g. where your process crashes or the machine hangs before setting things back as they were.