logoISU  

CS456 - Systems Programming

Spring 2025

Displaying ./code/stat/getPerms.c

/*

Takes as file, prints out numerical file types

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


the bitmask for the filetype field can be respresented by S_IFMT or 0170000

the bitmask for the permissions field is 0777

these are both octal values, hence the leading 0 in the number, which must be included
in order to represent octal values in C

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


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);
	}

	//getting numerical filetype
	//we are binary AND'ing the mode with the filetype bitmask to get the filetype
	mode_t filetype = st.st_mode & 0170000;	

	//getting numerical perms
	//binary AND'ing the mode with 0777 to get the file permissions
	mode_t fileperms = st.st_mode & 0777;

	//printing results
	printf("File Type: %o\nFile Permissions: %o\n", filetype, fileperms);

	return 0;

}