How does vim write a read-only file?

Sorry for the newbie question. I would like to know how vim manages to write a read-only file. I have 555 permissions for a text file. But when I open and write and do something: w !, the changes made by me to the file are saved. I wonder how vim does it in the background !!. Is this like temporarily changing permissions to 755 and writing to it and returning rights back? Please enlighten.

+5
source share
1 answer

EDIT: I initially answered with the correct, but ultimately irrelevant information on how UNIX permissions work: this is not what Vim did.

Indeed, you are right: when you release :w! , and you work on UNIX, Vim will add write permission if it needs to:

 /* When using ":w!" and the file was read-only: make it writable */ if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid() && vim_strchr(p_cpo, CPO_FWRITE) == NULL) { perm |= 0200; (void)mch_setperm(fname, perm); made_writable = TRUE; } 

and then reset back:

 if (made_writable) perm &= ~0200; /* reset 'w' bit for security reasons */ 

This is also reflected in the help:

Note. . This can change the permission and ownership of files and broken (symbolic) links. Add the 'W' flag to "cpoptions" to avoid this.

+7
source

All Articles