Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print directories in ascending order using scandir() in c

Tags:

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;
}
like image 995
LoveToCode Avatar asked Feb 11 '23 17:02

LoveToCode


1 Answers

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;
}
like image 197
ani627 Avatar answered Feb 16 '23 04:02

ani627