cfilesortingdirectorydirent.h

Sorting files in the directory including case sensitivity in C


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

Solution

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