|
CS456 - Systems Programming
Spring 2026
|
Displaying ./code/h3/filetype.c
/*
This takes a file, and depending on it's attributes, something happens
We get a file, and were going to do the following:
If it is a regular file:
- print the following
- name
- device_id
- inode
- permissions (in octal)
- size
If it is a directory:
- open the directory, print the contents that aren't hidden files
- print the count of the total number of files as well as the number of files that are hidden
If it is anything else:
- print the name of the file along with it's type (in octal).
- you can get the numerical value for that pretty easy
Do as well as you can here, we may be revisiting this program later
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
// what other header files wil i need?
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);
}
// call stat on the file we're passing in (YOU DO THIS)
// make sure you use the correct variant of stat (Hint: we want to detect links)
//don't forget to check the return value
struct stat st;
int rt = lstat(argv[1], &st);
if(rt < 0){
perror("stat failed");
exit(-1);
}
//check what type of file we have here
// also get the permissions here too
// for the if statements you can use a macro from man 7 inode
// or AND the mode with the mask value like in fileinfo.c
// which you need to do for the 'other' case anyway
// macro is probably easier
//if it's a regular file, print specified values
if(S_ISREG(st.st_mode)){
int perms = st.st_mode & 0777;
printf("Filename: %s\n", argv[1]);
printf("Device: %ld\n", st.st_dev);
printf("Inode: %ld\n",st.st_ino);
printf("Permissions: %o\n", perms);
printf("File Size: %ld\n",st.st_size);
} else if(S_ISDIR(st.st_mode)){
DIR *mydir;
struct dirent *file;
mydir = opendir(argv[1]);
//check return value of opendir
if(mydir == NULL){
perror("opendir failed");
exit(-2);
}
//keep counts of files
int count = 0;
int hidden = 0;
//reading through directory
while((file = readdir(mydir)) != NULL){
count++;
// checking if this is a hidden file ,
// denoted by a '.' period character in the first chaacter of filename
if(file->d_name[0] == '.'){
hidden++;
continue;
}
printf("%s\n", file->d_name);
}
printf("The directory %s has %d files, of which %d are hidden\n", argv[1], count, hidden);
closedir(mydir);
} else {
//get what filetype this file is
int type = st.st_mode & 0170000;
printf("Name: %s Type: %o\n", argv[1], type);
}
//if it's a directory,
// print the contents but not hidden files
// print the count of total files as well as hidden files
//anything else, just print the name along with it's file type in octal
return 0;
}
|