Archive

Archive for March, 2011

Change Unix File Permissions Using C

March 26, 2011 Leave a comment

This is a small program written in C used to change permissions of files in Unix.

You may ask why would someone want to use a C snippet instead of a quick “chmod” shell script?

Well, a simple “chown” script works just fine for cases where you don’t have a ridiculously large amount of files. Things get painfully slow when besides having millions of files you also have millions of directories. In those rare cases there is nothing faster than C.

If you have a 64 bit operating system you can compile this code with “-m64” flag for better performance.

#include
#include
#include
#include

#define PATH "/export/home/egloo"
#define UID 501
#define GID 501
#define NOTIFICATION_INTERVAL 10000

int file_count = 0;
char cmd[128];

static int callback(const char *fpath, const struct stat *sb, int typeflag) {
// Check if it's a file or a directory
if (typeflag == FTW_D || typeflag == FTW_F) {

// Apply new permissions
chown(fpath, UID, GID);

// Send progress notification
file_count++;
if ( 0 == ( file_count % NOTIFICATION_INTERVAL ) ){
fprintf( stderr, "%ld\n", file_count );
sprintf(cmd,"/bin/echo \"%i files processed\" | /bin/mail -s \"CHOWN PROGRESS\" user@domain.com", file_count);
system(cmd);
}
}

// Continue FTW
return 0;
}

int main(int argc, char **argv) {
ftw(PATH, callback, 256);
}