Concepts:
System calls opendir, readdir, stat, structure struct stat and structure struct dirent to manage with files and directories
Text:
Realize a program that reads the content of a direcoty and prints some information regarding the files contained in it. The name of the directory is the only parameter of the program.
The program must print:
FILE: <file_name> <file_dimension_in_bytes>
DIR: <directory_name>
The two special directories “.” (current directory) and “..”
(parent directory) should not be analyzed.
Example:
The program applied to a directory with name dir
that contains three subdirectories (dir1
, dir2
, and dir3
) and two files (file1
and file2
) with dimensions of 50
and 6
bytes respectively, must provide the following output:
$ ./directory dir DIR: dir/dir2 DIR: dir/dir1 DIR: dir/dir3 FILE: dir/file2 6 FILE: dir/file1 50
Solution:
#include <sys/types.h> /* for opendir, stat */ #include <dirent.h> /* for opendir */ #include <sys/stat.h> /* for stat */ #include <unistd.h> /* for stat */ #include <stdio.h> #include <stdlib.h> #include <string.h> #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 <pathname>\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); }