I am new to C programming and I'd like to implement chmod command on files of a dir and subdir. How can I change/show permissions with a C code? Could someone help with a example? I would appreciate if anyone can provide me a code.
Asked
Active
Viewed 4.5k times
3 Answers
14
There's a chmod function. From man 3p chmod:
SYNOPSIS
#include <sys/stat.h>
int chmod(const char *path, mode_t mode);
...
If you want to read the permissions, you'd use stat. From man 3p stat:
SYNOPSIS
#include <sys/stat.h>
int stat(const char *restrict path, struct stat *restrict buf);
...
If you want to do it recursively like you mentioned, you'll have to do the looping over results of readdir
yourself.

Cascabel
- 479,068
- 72
- 370
- 318
-
Thank you for the quick answer, but can I find somwhere a full code about it? – speed17 Mar 29 '10 at 17:07
-
I did, but I found just pieces. – speed17 Mar 29 '10 at 17:11
-
@user304414: Did you try the versions of the man pages I linked? They have real examples below them. – Cascabel Mar 29 '10 at 17:25
-
Yes, I did, but those are just examples, not a full program. I can learn just from a functioning program code. – speed17 Mar 29 '10 at 17:28
-
@user304414: Those are full examples of the calls to these functions. If you want a full program, wrap it in a main, declare the necessary variables... – Cascabel Mar 29 '10 at 17:33
1
a example:(show/test permissions)
struct stat st;
int ret = stat(filename, &st);
if(ret != 0) {
return false;
}
if((st.st_mode & S_IWOTH) == S_IWOTH) {
} else {
}

songhir
- 3,393
- 3
- 19
- 27