I've been reading the man pages of scandir(), alphasort() and have evidently crammed them all. But still can't figure out how to implement a custom comparision function.

Here's my code:

#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);

}

Easy to see that am trying to alphabetically sort file names irrespective of hidden and normal files (leading '.').

But a computer will always do what you tell it to but not what you want it to.

有帮助吗?

解决方案

The sort routine mySort is the issue. This compare function needs to be of type int (*)(const struct dirent **, const struct dirent **). For example:

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);
}

Recommend changing to

int mySort(const struct dirent **e1, const struct dirent **e2);
int (*fnPtr)(const struct dirent **e1, const struct dirent **e2);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top