logoISU  

CS456 - Systems Programming

Spring 2025

Displaying ./code/stat/perms.c

/*

Takes as file, prints out the kinds of permissions it has

man 7 inode has info on the mask values for file permissions

The mode of a file consists of two different parts
0040755 - The left three (004) octal digit represents the file type,
	  The middle digit (0) is the set-group ID bit 
          the right three (755)represent the file permissions

*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

//a function that checks file permissions
int checkPermissions(int mode, int perm);

int main (int argc, char **argv){

	//prints usage statement if file not provided
	if(argc < 2){
		fprintf(stderr, "Usage %s file\n", argv[0]);
		exit(1);
	}


	struct stat st; // this calls the stat structure

	int rt;                   //variable to check the return value for stat
	rt = lstat(argv[1], &st);  //call stat on the file, storing the data in st

	//check return value of rt, 
	if(rt < 0){ 
		perror("Error"); 
		exit(-1);
	}
	
	//checking if owner has certain permissions
	int read, write, exec;
	read = checkPermissions(st.st_mode, S_IRUSR); //check if owner has read
	write = checkPermissions(st.st_mode, S_IWUSR); //check if owner has write
	exec = checkPermissions(st.st_mode, S_IXUSR); //check if owner has execute

	//printing results

	printf("Does owner has permission enabled for %s file:\n read: %d\n write: %d\n execute: %d\n", argv[1], read, write, exec);

	return 0;

}

//checking if file has a certain permissions
int checkPermissions(int mode, int perm){        
        if((mode & perm) == perm)
            return 1;
         else    
            return 0; 
}