I'm trying to code a simple function to sort the content of a directory. The Thing is, it comes out in alphabetical order, regardless of uppercase or lowercase. I'd like to sort this content in ASCII order.
example: I got 4 files, named Art, boat, Cat and donkey. My actual code sort them in this order, while i'd like to get Art, Cat, boat and donkey.
void list_dir(char *str){
DIR *rep = NULL;
struct dirent* read_file = NULL;
rep = opendir(str);
if (!rep)
{
ft_putstr("ft_ls: ");
perror(str);
ft_putchar('\n');
}
while((read_file = readdir(rep)) != NULL)
{
if (read_file->d_name[0] != '.')
{
ft_putstr(read_file->d_name);
ft_putchar('\n');
}
}
}
readdir(3) does not normally sort at all, it lists the entries in directory order. If the list is sorted, either the files were created sorted, or the OS sorts them.
In order to sort the output yourself, put the list of names into an array then sort it e.g. with qsort(3) and strcmp(3).
Alternatively, just pipe the output through sort(1). Do make sure that the
LC_COLLATION
environment variable is set proper. For example, run./yourprogram | (unset LC_ALL; LC_CTYPE=en_US.UTF-8 LC_COLLATE=C sort)
.