logoISU  

CS456 - Systems Programming

Spring 2023

Displaying ./code/h3/main.c

/* 

this is where  the main function will go

*/

#include "myls.h" 

int main(int argc, char **argv){

	// note: i replaced  "struct stat" with an alternative name
	//       using the typedef keyword as seen in myls.h

	DIR   *mydir;  // defining a pointer to a directory
	DIRENT *file;  // defining the dirent struct
	STAT      st;  // the stat struct
	int      opt;  // using an integer to store what options were passed through


	char  options[BUF];  //setting buffer for options
    char filename[BUF];  //setting buffer for filename

	
	processArgs(argc, argv, options, filename); // processing the command line arguments
    	//first two arguments are argc argv
    	//last two arguments are where we will store the options and the filename

	opt = flags(options); //processing the option string 
		// this turns the string into an integer value where certain bits are set
		// to 1 based on what options were passed in


	if(opt == -1) exit(0); // if opt returns -1, just exit the program
		// here, a -h option was passed in, so we just print a usage statement
	    // and then exit

	stat(filename, &st); // calling stat on filename, store all data in st

	//check if file is a directory
		//if not, say so and exit
	if(S_ISDIR(st.st_mode) == 0) {
		fprintf(stderr, "%s is not a directory\n", filename);
		exit(-1);
	}

	//open the directory
	mydir = opendir(filename); 

	//check return value of opendir 
		//if it is NULL, say so and exit the program
	if(mydir == NULL){
		fprintf(stderr, "failed to open directory\n");
		exit(-1);
	} 

	int count = 0; 


	//now we loop through the directory
	while((file = readdir(mydir)) != NULL){

		//check if current file is a hidden file
			//if so, check if the -a option is turned on
			// in other words, is that bit set to 1?

		if(isHiddenFile(file->d_name)){
			if(isHiddenOption(opt) == 0)
				continue;
		}

		//now check if the user entered the -l option
			//if so, run the printLongFormat function
		if(isLongFormat(opt))
			printLongFormat(st);

		//print file name 
		printf("%s\n", file->d_name);
		count++;

	}

	if(isCount(opt)){
		printf("%d files shown\n", count);
	}

	//close the directory
	closedir(mydir);

	return 0;


}