1

I have a C code snippet: I have used dirent.h and used opendir and readdir to read the files I am doing a ls command duplicate using c code , for that the file should be is ascending order and case sensitivity also to be included.

#include <stdio.h>
#include <dirent.h>

int main(void)
{
    DIR *d;
    struct dirent *dir;
    d = opendir(".");
    printf("d: %d \n",d);
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            printf("\n %s \n", dir->d_name);
        }
        closedir(d);
    }
    else
    {
        printf("soory");
    }

    return (0);
}

I got result as

krishna-R
stat.c
temp
Bing
TempFolder
button

What i want is

Bing
button
krishna-R
stat.c
TempFolder
temp
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
  • 2
    Then collect the filenames and pass them through a sorting function. – Eugene Sh. Jan 13 '21 at 15:55
  • 1
    I think you've confused "case sensitive sort" vs. "no sort whatsoever". You're doing the latter. If you want the list sorted - then you need to manually sort it! – paulsm4 Jan 13 '21 at 15:56
  • 1
    You could create an array of struct dirent and then pass the array to qsort. You would need to write a comparator function to compare two dirents. This might help: https://stackoverflow.com/a/55230286/4903336 – Dex Jan 13 '21 at 15:57

1 Answers1

0
#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main(void)
{
    char array[50][30]={};
    int i=0, j=0, k=0;
    DIR *d;
    struct dirent *dir;
    d = opendir(".");
    printf("d: %d \n",d);    
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            strcpy(array[i], dir->d_name);
            i++;
        }
        for (k = 0; k <= i; k++)    /* Sorting files alphabetically */
            for (j = k + 1; j <= i; j++)
            {
                if (strcasecmp(array[k], array[j]) > 0)
                {
                    strcpy(tmp, array[k]);
                    strcpy(array[k], array[j]);
                    strcpy(array[j], tmp);
                }
            }
        closedir(d);
      }
      for (int a = 0 ; a < i ; a++)
      {
          printf("%s \n",array[a]);
      }
      return 0;
}
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88