Manpage scandir()原型怪异

une*_*ist 6 c manpage

我有scandir()的问题:联机帮助页包含这个原型:

int scandir(const char *dir, struct dirent ***namelist,
  int (*filter)(const struct dirent *),
  int (*compar)(const struct dirent **, const struct dirent **));
Run Code Online (Sandbox Code Playgroud)

所以我有这个:

static inline int
RubyCompare(const struct dirent **a,
  const struct dirent **b)
{
  return(strcmp((*a)->d_name, (*b)->d_name));
}
Run Code Online (Sandbox Code Playgroud)

这是电话:

num = scandir(buf, &entries, NULL, RubyCompare);
Run Code Online (Sandbox Code Playgroud)

最后,编译器说:

warning: passing argument 4 of ‘scandir’ from incompatible pointer type
Run Code Online (Sandbox Code Playgroud)

编译器是gcc-4.3.2,我的CFLAGS如下:

-Wall -Wpointer-arith -Wstrict-prototypes -Wunused -Wshadow -std=gnu99
Run Code Online (Sandbox Code Playgroud)

这个警告是什么意思?RubyCompare的声明看起来对我来说是正确的,除了警告代码完全可行.

Chr*_*ung 5

实际上,没有这样的约束,你不能将指针传递给内联函数.inline关键字仅作为编译器提示内联调用的提示.

问题是scandir()的联机帮助页有点误导.第4个参数的原型实际上是int(*cmp)(const void*,const void*).

因此,您需要更改代码,如下所示:

static inline int RubyCompare(const void *a, const void *b)
{
    return(strcmp((*(struct dirent **)a)->d_name, 
                  (*(struct dirent **)b)->d_name));
}
Run Code Online (Sandbox Code Playgroud)

我不确定你为什么写这个函数,因为你可以使用提供的alphasort compare函数:

num = scandir(buf, &entries, NULL, alphasort);
Run Code Online (Sandbox Code Playgroud)