#ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include static int rflag, aflag; /*Arguments*/ static int myls(char*); static void usage(); int main(int argc, char *argv[]) { int c; char pathname[MAXPATHLEN]; /*path to execute command */ extern char *optarg; extern int optind, optopt; /*parsing command options */ while ((c = getopt(argc, argv, "aRr")) != -1) { switch (c) { case 'a': /*Show hidden option */ aflag = 1; break; case 'R':/*Recursively option */ case 'r':/*compatibility */ rflag = 1; break; default: /*Else show usage */ usage(); } } if (argv[optind] == 0) /*if not a path for ls given */ getwd(pathname); /*use Current working path */ else strcpy(pathname,argv[optind]); /*LS on path given */ myls(pathname); /*Execute command ls */ return EXIT_SUCCESS; /*Exit */ } /*Handles the files shown */ static int file_select(struct direct *entry) { /*not Show All mode */ if (aflag != 1) if (entry->d_name[0] == '.') return 0; /*dont show hidden files */ return !0; /*else show all without check */ } static int myls(char *path) { int filecount,i; char tmp[MAXPATHLEN]; struct direct **files; struct stat *buf = (struct stat*)malloc(sizeof(struct stat)); int file_select(struct direct*); if (path == NULL) /*Path to LS */ { fprintf(stderr, "Error on getting PATH"); exit(EXIT_FAILURE); /*Terminate program */ } stat(path,buf); if (!S_ISDIR(buf->st_mode)) { fprintf(stderr, "Fatal error - PATH given is not a directory"); exit(EXIT_FAILURE); } filecount = scandir(path,&files,file_select,alphasort); /*scanning our path */ printf("%s:\ntotal %d\n",path,filecount); /*printing header and counted files */ /*Printing directory containings */ for (i=0; i < filecount; i++) printf("%s\n",files[i]->d_name); /*-r -R Recursively mode */ if (rflag == 1){ for (i=0; i < filecount; i++) /*Search again files and myls() directories */ { if (!(strcmp(files[i]->d_name,".") == 0 || strcmp(files[i]->d_name,"..") == 0)){ /*skip . and .. */ strcpy(tmp,path); /*Creating a full path name of each file*/ strncat(tmp,"/",MAXPATHLEN); strncat(tmp,files[i]->d_name,MAXPATHLEN); stat(tmp,buf); /*get file stat */ if (S_ISDIR(buf->st_mode)) /*got a directory */ { printf("\n"); myls(tmp); } } } } return EXIT_SUCCESS; } static void usage() { fprintf(stderr, "%s\n%s\n", "usage: lscomp [-aRr] [FILE] ...", " List information about the FILEs"); exit(EX_USAGE); }