2

我正在学习 C 并且我有这个实现来对文件和文件夹进行排序,但这不区分大小写:

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

如果我有 a.txt、b.txt、C.txt 和 z.txt,它将按以下顺序排序:C.txt、a.txt、b.txt、z.txt。我希望这样排序不区分大小写:a.txt、b.txt、C.txt、z.txt

4

1 回答 1

2

scandir用这个原型定义:

int scandir(const char *restrict dirp,
            struct dirent ***restrict namelist,
            int (*filter)(const struct dirent *),
            int (*compar)(const struct dirent **,
                          const struct dirent **));

该函数alphasort按字典顺序对文件名进行排序,因此区分大小写。如果您想要不区分大小写的排序,请使用不同的比较函数:

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

scandir和都是strcasecmpPOSIX 函数:strcasecmp极有可能在支持scandir和定义<strings.h>.

修改器版本:

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

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

int main(void) {
    struct dirent **namelist;
    int n;

    n = scandir(".", &namelist, NULL, alphasort_no_case);
    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);
    }
    return 0;
}
于 2021-12-31T12:16:51.437 回答