logoISU  

CS456 - Systems Programming

Spring 2026

Displaying ./code/feb26/getPerms.c

/*

Takes a file, prints out numerical file types

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

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
				  // lstat is used here so we can detect links
	
	//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);

	// macro that checks if file is a regular file
	// more info in man 7 inode
	if(S_ISREG(st.st_mode))
		printf("This is a regular file\n");

	
	// character device - 20000
	// regular file - 100000
	// directory - 40000
	// symbolic link - 120000
	// note that the leading 0 is not printed

	return 0;


}