【问题标题】:How to implement custom compar() for scandir()如何为scandir()实现自定义比较()
【发布时间】:2013-08-22 12:40:49
【问题描述】:

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

}

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

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

【问题讨论】:

    标签: c linux sorting alphabetical scandir


    【解决方案1】:

    排序例程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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      相关资源
      最近更新 更多