2

我一直在阅读 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);

}

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

但是计算机总是会做你告诉它的事情,而不是你想要它做的事情。

4

1 回答 1

1

排序例程mySort是问题所在。这个比较函数需要是 type 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);
于 2013-08-22T14:07:18.477 回答