Issue
I know pretty much how to use chmod
directly from the command line. But I'm not quite sure if we can mimic its
chmod o+t filename
function. I usually call it directly with:
chmod(filename, 0666)
But instead of setting the permissions, I want to know how to add a permission without affecting the other ones, like chmod o+t filename
. Something like chmod(filename, 1777)
will also set the sticky bit, but it also sets all the other bits. What number should we pass to chmod
to let it only change the sticky bit? thanks in advance.
Solution
As mentioned in comments, first read current mode bits with stat(), then do chmod().
The thing to take home with you is that you shouldn't be working with numeric values directly but instead trust those defined in header files. See man 2 chmod
for what is available.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char **argv) {
struct stat st;
if(argc < 1) return 2;
if(stat(argv[1], &st) != 0) {
perror(argv[1]);
return 2;
}
printf("mode before chmod() = %o\n", st.st_mode);
if(chmod(argv[1], st.st_mode | S_ISVTX) != 0) {
perror(argv[1]);
return 1;
}
if(stat(argv[1], &st) != 0) {
perror(argv[1]);
return 2;
}
printf("mode after chmod() = %o\n", st.st_mode);
return 0;
}
Have fun with homework!
Answered By - user2845360 Answer Checked By - Marie Seifert (WPSolving Admin)