作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我一直在阅读 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/
我是一名优秀的程序员,十分优秀!