I'm learning C and I have this implementation to sort the files and folders, but this isn't case insensitive:
#include <dirent.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
struct dirent **namelist;
int n;
n = scandir(".", &namelist, NULL, alphasort);
if (n < 0)
perror("scandir");
else {
printf("Inside else, n = %d\n", n);
while (n--) {
printf("%s\n", namelist[n]->d_name);
free(namelist[n]);
}
free(namelist);
}
}
And if I have a.txt, b.txt, C.txt and z.txt it will sort in this order: C.txt, a.txt, b.txt, z.txt. I want this to be sorted case insensitive like this: a.txt, b.txt, C.txt, z.txt
scandiris defined with this prototype:The function
alphasortsorts the filenames in lexicographical order, hence case-sensitive order. If you want case insensitive sorting, use a different comparison function:Both
scandirandstrcasecmpare POSIX functions:strcasecmpis highly likely to be available on systems that supportscandirand defined in<strings.h>.Modifier version: