Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider a hierarchical file-system consisting of directories, each of which pos

ID: 3940062 • Letter: C

Question

Consider a hierarchical file-system consisting of directories, each of which possibly contains files and other sub-directories There are no other types of file-system objects in this filesystem. Next, consider the C99 function countEntries(), whose prototype follows: void countEntries(char *dirName, int *nFiles, int *nDirs); The parameter named dirName points to a character string, providing the name of a directory to be recursively explored for files and subdirectories. After countEntries() has explored everything below the named directory, the parameters nFiles and nDirs should provide, to the calling function, the number of files and directories found, respectively. If countEntries() finds a directory that cannot be opened, it should report an error and continue its processing (i.e. the function should not exit on such an error). Write the function countEntries() in C99.

Explanation / Answer

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<dirent.h>
#include<sys/stat.h>
#include<unistd.h>
void countEntries(char *dirname, int *nDirs, int *nFiles);
main(int argc,char **argv)
{
        int nDirs, nFiles;
        char a[100];
        strcpy(a, "/home/usr/");// in 2 argument provide your directory path
        if(argc == 2){

                strcat(a, argv[1]);
        }
        else {
                printf("Usage : ./a.out dirname ");
                return ;
        }
        countEntries(a, &nDirs, &nFiles);
        printf("nDirs = %d, nFiles=%d ", nDirs, nFiles);
}
void countEntries(char *dirname, int *nDirs, int *nFiles)
{
        DIR *dp;   char b[400];
        static int D=0, F=0;
        struct dirent *d,*d1;
        struct stat s,s1;
        dp=opendir(dirname);
        while(d=readdir(dp)) {
                if(d->d_name[0]!='.')
                {
                        strcpy(b,dirname);
                        strcat(b,"/");
                        strcat(b,d->d_name);
                        stat(b,&s1);
                        if(S_ISDIR(s1.st_mode))
                        {
                                D++;
                                countEntries(b, nDirs, nFiles);
                        }
                        else
                        {
                                F++;
                        }
               }
       }          
       *nDirs = D;
        *nFiles = F;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote