0

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');
    }
}

}

4

2 回答 2

0

readdir(3)通常根本不排序,它按目录顺序列出条目。如果列表已排序,则创建的文件已排序,或者操作系统对其进行排序。

为了自己对输出进行排序,请将名称列表放入一个数组中,然后使用qsort(3)strcmp(3)对其进行排序。

或者,只需通过sort(1)管道输出。请确保LC_COLLATION环境变量设置正确。例如,运行./yourprogram | (unset LC_ALL; LC_CTYPE=en_US.UTF-8 LC_COLLATE=C sort).

于 2013-12-09T17:49:44.793 回答
0

通过使用用户定义的过滤器和比较器调用scandir是一个简单的解决方案恕我直言。这是代码:

#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

static int my_dir_filter(const struct dirent* dir);
static int my_dir_comparator(const struct dirent**, const struct dirent**);

int main(int argc, char* const* argv) {
    struct dirent** ent_list_ = NULL;
    int r = scandir(".", &ent_list_, my_dir_filter, my_dir_comparator);
    for (int i = 0; i < r; ++i)
        printf("No. %-3d [%s]\n", i + 1, ent_list_[i]->d_name);
    for (int i = 0; i < r; ++i)
        free(ent_list_[i]);
    free(ent_list_);
    return r < 0 ? 1 : 0;
}

int my_dir_filter(const struct dirent* dir) {
    return (dir->d_type == DT_REG) ? 1 : 0;
}

int my_dir_comparator(const struct dirent** lhs, const struct dirent** rhs) {
    return strcasecmp((*lhs)->d_name, (*rhs)->d_name);
}

和测试结果:

$ ls|LANG=C sort   ## in ASCII order
Art
Cat
boat
donkey
$ ../a.out         ## in my_dir_comparator order
No. 1   [Art]
No. 2   [boat]
No. 3   [Cat]
No. 4   [donkey]
于 2016-11-09T09:25:49.463 回答