9

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
speed17
  • 95
  • 1
  • 2
  • 6

3 Answers3

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
2

with the GNU C library you should be able to do it directly with

int chmod (const char *filename, mode_t mode)
int chown (const char *filename, uid_t owner, gid_t group)

check it out here.. all these functions are in sys/stat.h

Jack
  • 131,802
  • 30
  • 241
  • 343
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