gpt4 book ai didi

c - 如何为 scandir() 实现自定义 compar()

转载 作者:太空狗 更新时间:2023-10-29 12:33:51 24 4
gpt4 key购买 nike

我一直在阅读 scandir()、alphasort() 的手册页,显然已经将它们全部塞满了。但仍然无法弄清楚如何实现自定义比较功能。

这是我的代码:

#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>

int mySort(char*, char*);
int (*fnPtr)(char*, char*);

int main(){
struct dirent **entryList;
fnPtr = &mySort;
int count = scandir(".",&entryList,NULL,fnptr);
for(count--;count>=0;count--){
printf("%s\n",entryList[count]->d_name);
}
return 0;
}

int mySort(const void* a, const void* b){
char *aNew, *bNew;
if(a[0] == '.'){
*aNew = removeDot(a);
}
else{
aNew = a;
}

if(b[0] == '.'){
*bNew = removeDot(b);
}
else{
bNew = b;
}
return alphasort(aNew, bNew);

很容易看出我正在尝试按字母顺序对文件名进行排序,而不考虑隐藏文件和普通文件(前导“.”)。

但是计算机总是会按照您的吩咐去做,而不是按照您的意愿去做。

最佳答案

排序例程 mySort 是问题所在。此比较函数需要是 int (*)(const struct dirent **, const struct dirent **) 类型。例如:

int mySort(const struct dirent **e1, const struct dirent **e2) {
const char *a = (*e1)->d_name;
const char *b = (*e2)->d_name;
return strcmp(a, b);
}

建议改为

int mySort(const struct dirent **e1, const struct dirent **e2);
int (*fnPtr)(const struct dirent **e1, const struct dirent **e2);

关于c - 如何为 scandir() 实现自定义 compar(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18380760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com