#include /* for opendir, stat */ #include /* for opendir */ #include /* for stat */ #include /* for stat */ #include #include #include #define N 100 int main (int argc, char *argv[]) { DIR *dp; struct stat statbuf; struct dirent *dirp; char name[N], *dirName; if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); exit(EXIT_FAILURE); } /* Open the directory */ dirName = argv[1]; if ( (dp = opendir(dirName)) == NULL) { fprintf(stderr, "Error on opening directory: %s\n", argv[1]); exit(EXIT_FAILURE); } /* Cycle on the elements contained in the directory */ while ( (dirp = readdir(dp)) != NULL) { /* generate the path of an element contained in the directory */ sprintf (name, "%s/%s", dirName, dirp->d_name); /* Check if the element is a special directory (i.e., "." or "..") */ if (strcmp(dirp->d_name, ".") != 0 && strcmp(dirp->d_name, "..") != 0) { /* Analyze the element */ if (stat(name, &statbuf) < 0 ) { fprintf (stderr, "Error executing system call stat\n"); exit (EXIT_FAILURE); } if (S_ISDIR(statbuf.st_mode)) { /* If it is a directory */ printf("DIR: %s\n", name); } else if (S_ISREG(statbuf.st_mode)) { /* If it is a file */ printf("FILE: %s %ld\n", name, (long)statbuf.st_size); } } } /* Chiusura della directory */ if (closedir(dp) < 0) { fprintf (stderr, "Close the directory\n"); exit (EXIT_FAILURE); } return (EXIT_SUCCESS); }