logoISU  

CS456 - Systems Programming

Spring 2026

Displaying ./code/mar18/printdir.c

/*

given a directory, prints it's contents.

or doesn't, if it isn't a directory


*/

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

	//getting information on the file we're passing in
	struct stat st; 
	int rt;
	rt = lstat(argv[1], &st);

	//check return value of lstat
	if(rt < 0){
		perror("Error: Stat failed");
		exit(-1);
	}

	//using the S_ISDIR macro from man 7 inode to check if given file is a directory
	if(!S_ISDIR(st.st_mode)){
        	fprintf(stderr, "Error: %s is not a directory\n", argv[1]);
		exit(-2);
	}

	DIR *mydir;       //defining pointer to directory
	struct dirent *file; //accessing the dirent struct, defined in dirent.h

	mydir = opendir(argv[1]); //opening a directory

	if(mydir == NULL){
		perror("opendir failed");
		exit(-2);
	}

	//printing counts of files
	int count = 0;
	int hidden = 0;

	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++;

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

	return 0;

}