Question: Write a C program myls2 whose behavior resembles that of the system command ls. myls2 must print the names of files in the current directory
Write a C program myls2 whose behavior resembles that of the system command ls. myls2 must print the names of files in the current directory in columns of equal width. myls2 must accept the following parameters:
$ myls2 [-rs]
-s switch sorts the filenames in the lexicographical order. The file names must be arranged in sequence so that the names in column 1 are followed by the names in column 2, and so on.
-r switch sorts the filenames in the reverse lexicographical order.
$ ls dirA file2.txt file5.txt file8.txt file0.txt file3.txt file6.txt file9.txt file1.txt file4.txt file7.txt $ cd dirA $ ls file0a.txt file444444444a.txt file8a.txt file1a.txt file5a.txt file9a.txt file2a.txt file6a.txt file3a.txt file7a.txt
Code for LS1:
#include
int main(int argc, char *argv[]){
struct dirent *direntp; DIR *d; char path[50]; char opt[3]; char data[10000][50]; char temp[50]; int i,j; int count = 0;
strcpy(opt,""); if (argc == 1){ strcpy(path,"."); //stay in current directory if no arguments } if (argc == 2){ if (argv[1][0] == '-'){ //if there is a -a, -s, or -r parameter strcpy(opt,argv[1]); //copy the parameter strcpy(path,"."); //path is the current directory } else { strcpy(path,argv[1]); //otherwise the parameter becomes a path } }
if (argc == 3){ strcpy(opt, argv[1]); strcpy(path, argv[2]); }
if ((d = opendir(path)) == NULL){ perror("Failed to open directory"); return 1; } while((direntp = readdir(d)) != NULL){ strcpy(data[count],direntp->d_name); count++;
} while((closedir(d) == -1) && (errno == EINTR)); if (strcmp(opt,"-a") == 0){ for (i = 0; i } else { for (i = 0; i } return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
