logoISU  

CS456 - Systems Programming

Spring 2026

Displaying ./code/feb26/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 is generally represented by an octal number and consists of three different parts
0040755 - The left three digits (004) represents the file type,
	- The middle digit (0) is the set-group ID bit 
        - The right three digits (755) represent the file permissions

To check permissions, we Binary AND the mode with one of the mask values.

*/
#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 using macro values found in man 7 inode 
	// S_IRUSR = 00400  
	// S_IWUSR = 00200
	// S_IXUSR = 00100
	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) // AND'ing the mode with the mask value and seeing if it results in mask value 
            return 1;             // if true, then the file does have that permission
         else    
            return 0; 
}