logoISU  

CS456 - Systems Programming

Spring 2026

Displaying ./code/final/final.c

/*

CS 456/556 Final Exam

Directory Analysis:

You will take a file through the command line and do the following:
- If it is anything other than a directory, print a message saying it's not a directory and exit.
- if it is a directory:
	- we are counting the following
		- total number of files
		- regular files
		- directories
		- all other files that aren't regular files or directories
    - we will also get the total size (in bytes) of all regular files combined

Hint: look at the mar18 directory of the in-class code for a program that prints directories


compile with gcc -o final final.c

*/

//header files
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.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);
	}

	// calling stat on the file we're passing in through the command line


	//check return value of stat, if it fails, get an error message and exit


	//if this file passed in is NOT a directory, say so and exit


	//since we're here, call the directory struct 

	//open the directory
	mydir = opendir(argv[1]);

	//check return value of opendir

	//set up counts for each type of file
	int count = 0;
	int reg = 0;
	int dir = 0;
	int other = 0;

	//set up count for total file size
	int sizereg = 0;

	// read through directory
	while((file = readdir(mydir)) != NULL){
		
		    //increment count for number of files
		
		// lstat doesn't like the file->d_name
		// so we need to create a buffer for the path
		// use snprintf to concatinate the directory you passed in and the filename, 
		// snprintf is safer to use than strcat, as you aren't modifying original string
		char path[1024];
		snprintf(path, 1024, "%s/%s", argv[1], file->d_name);	

		// calling stat on our path
		struct stat fi;
		rt = lstat(path, &fi);

		//if stat, for some reason fails, just continue
		if(rt < 0) continue;

		// if file is a regular file
			//increase count of regular files
			 //get size of file, add to cumulative total
		//else if file is a directory
			//increase count of directories
		// anything else
			 //increase count of other files
		}

	}	
	
	closedir(mydir); //close directory

	//print message with information	
	printf("The %s directory has %d files, out of which %d are regular files, %d directories, and %d other files\n", argv[1], count, reg, dir, other);
	printf("Total Size of all regular files: %d bytes\n", sizereg);

	return 0;

}