我正在學習 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
uj5u.com熱心網友回復:
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并strcasecmp有POSIX的功能: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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/400311.html
上一篇:如何使用C語言顯示組合四叉樹?
