-1

I need to sort file names in alphanumeric descending order. I have written the following code In C, but it's sorting in alphabetic only order I guess as file A2 is read before A11. I am using scandir with alphasort

Thanks for the help

   struct dirent **vl_lecture = NULL;
   DIR *vl_repertoire = NULL;
   //I open the directory with opendir
   vl_repertoire = opendir(vg_alias_rep_fichier.arr); 
   ...//code
   int n = scandir(vg_alias_rep_fichier.arr,&vl_lecture, NULL, alphasort);
   // I use while to perform some operations with file names ...
Saad
  • 9
  • 1
  • 4
    Does this answer your question? [Natural sort in C - "array of strings, containing numbers and letters"](https://stackoverflow.com/questions/1343840/natural-sort-in-c-array-of-strings-containing-numbers-and-letters) – user14063792468 Feb 04 '21 at 14:25
  • I could not find any working algorithm. Thanks for the help – Saad Feb 05 '21 at 12:52

1 Answers1

0

alphasort sorts strings in descending order. That's why you see A2 come before A11. Supply your own function

#include <string.h>

int
alphasort2 (const struct dirent **a, const struct dirent **b)
{
  return -strcoll ((*a)->d_name, (*b)->d_name);
}

//..
int n = scandir(vg_alias_rep_fichier.arr,&vl_lecture, NULL, alphasort2);

The code is based on the implementation of alphasort.

user2233706
  • 6,148
  • 5
  • 44
  • 86
  • I need to define my own function not to reverse alphasort. The problem is that I am not good enough in C to write it. Thanks for the help – Saad Feb 05 '21 at 12:48
  • That should give show you how to write a custom function. ```(*a)->d_name``` is a string, so you can call ```strcmp```. The other fields in direct are also accessible. – user2233706 Feb 05 '21 at 14:20