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

Write a C program myls whose behavior resembles that of the system command ls. m

ID: 3724172 • 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:

$ myls [-rs]

-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 names.
Consider using the qsort() library function that implements the quicksort algorithm to sort an array.

$ ls
dirA file2.txt file5.txt file8.txt
file0.txt file3.txt file6.txt file9.txt
file1.txt file4.txt file7.txt

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;
}

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