Write a C program myls whose behavior resembles that of the system command ls. m
ID: 3722781 • Letter: W
Question
Write a C program myls whose behavior resembles that of the system command ls. myls must print the names of files in the current directory in columns of equal width. myls must accept the following parameters:
-s switch sorts the filenames in alphabetical 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 alphabetical order.
When no switches are present, myls does not need to sort the file name.
Consider using the qsort() library function that implements the quicksort algorithm to sort an array.
Explanation / Answer
#include<dirent.h>
#include<errno.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int cstring_cmp(const void *a, const void *b)
{
return strcmp((char *)a, (char *)b);
}
int main(int argc, char *argv[]){
struct dirent *direntp;
DIR *d;
char path[50];
char opt[3];
char data[20000][50];
char data1[20000][50];
char temp[50];
int i,j;
strcpy(opt,"");
strcpy(path,".");
if (argc == 2){
if (argv[1][0] == '-'){
strcpy(opt,argv[1]);
}
}
if ((d = opendir(path)) == NULL){
perror("Failed to open directory");
return 1;
}
int count = 0;
while((direntp = readdir(d)) != NULL){
//printf("%s %d ",direntp->d_name,count);
strcpy(data[count],direntp->d_name);
count++;
}
while((closedir(d) == -1) && (errno == EINTR));
if (strcmp(opt,"-s") == 0){
qsort(data, count, sizeof(char *), cstring_cmp);
for (i = 0; i<count; i++)
if (data[i][0] != '.')
printf("%-15s ",data[i]);
}
else if (strcmp(opt,"-r") == 0){
for (i = 0; i<count; i++){
for (j=i+1; j<count; j++){
if (strcmp(data[i],data[j]) < 0){
strcpy(temp,data[i]);
strcpy(data[i],data[j]);
strcpy(data[j],temp);
}
}
}
for (i = 0; i<count; i++)
if (data[i][0] != '.')
printf("%s ",data[i]);
}
else {
for (i = 0; i<count; i++)
if (data[i][0] != '.')
printf("%s ",data[i]);
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.