views:

830

answers:

3

How can I programmatically lock/unlock, or otherwise prevent/enable editing, a source file on Linux using C++.

I want to be able to lock source file so that if I open it in an editor it will not allow me to save back to the same source file.

I am thinking of maybe changing the permissions to read-only (and change it back to read-write later): how do I do that from C++?

+5  A: 

Try man fchmod:

NAME
       chmod, fchmod - change permissions of a file

SYNOPSIS
       #include <sys/types.h>
       #include <sys/stat.h>

       int chmod(const char *path, mode_t mode);
       int fchmod(int fildes, mode_t mode);
David Dibben
slashmais
+1  A: 

Why aren't you using a source code management tool like CVS or Subversion? CVS does nice locking (so does Subversion). More importantly, you have the history of changes. Better still (with CVS anyway) you have to make the step of doing a "checkout" to make the file writeable.

S.Lott
slashmais
Ummm... That often leads to a hopeless bias. It's too easy to deprecate the solution everyone else uses because it wasn't your first idea on the subject.
S.Lott
+1  A: 

Yes, it is a bit hard to tell what you are looking for

  • Security against other users editing you files -> use "chmod, fchmod"

  • Security against you yourself accidentally messing with your source files -> you should really change your thinking and use a source control tool. Like Subversion (SVN) or even better Mercurial.

anders.norgaard