LoveToCode
LoveToCode

Reputation: 306

Print directories in ascending order using scandir() in c

While using scandir() it uses alphasort to sort the list of directory content in reverse order. Now how to print directories in ascending order using scandir() in c.

. and .. must be on top.

Here is the code:


#include<stdio.h>
#include <dirent.h>
#include<string.h>
#include<sys/dir.h>
#include<malloc.h>
int main(void)
{
   struct dirent **namelist;
   int n;

   n = scandir(".", &namelist,NULL,alphasort);
   if (n < 0)
      perror("scandir");
   else {
      while (n--) {
         printf("%s\n", namelist[n]->d_name);
         free(namelist[n]);
      }
      free(namelist);
   }
 return 0;
}

Upvotes: 5

Views: 8308

Answers (1)

ani627
ani627

Reputation: 6067

When you call alphasort it will sort the entries in ascending order.

In your code you have printed it in reverse order.

To print in ascending order you need to start from index 0.


For example:

#include<stdio.h>
#include <dirent.h>
#include<string.h>
#include<sys/dir.h>
int main(void)
{
   struct dirent **namelist;
   int n;
   int i=0;
   n = scandir(".", &namelist,NULL,alphasort);
   if (n < 0)
      perror("scandir");
   else {
      while (i<n) {
         printf("%s\n", namelist[i]->d_name);
         free(namelist[i]);
         ++i;
      }
      free(namelist);
   }
 return 0;
}

Upvotes: 9

Related Questions