【问题标题】:scandir in c - sel function implementationc - sel函数实现中的scandir
【发布时间】:2018-10-27 20:47:11
【问题描述】:

man scandir 给了我scandir 函数的以下结构:

int scandir(const char *dirp, struct dirent ***namelist,
              int (*filter)(const struct dirent *),
              int (*compar)(const struct dirent **, const struct dirent **));

假设我定义如下:

struct dirent **namelist;
int len = scandir('.', &namelist, NULL, NULL)

这会列出当前文件夹中的所有文件和文件夹名称。但是假设我有如下结构的filtercompar 函数:

int (*filter)(const struct dirent *) {
}

与比较类似,我想根据某些条件调用此过滤器函数或仅调用 NULL

if (some criteria) int *filters = NULL;
else int* filters = &filter
int len = scandir('.', &namelist, filters, NULL)

但这会导致指针错误。有没有办法解决这个问题?

【问题讨论】:

  • “这给出了指针错误”:你能分享确切的错误信息吗?在编译期间?执行期间?

标签: c scandir


【解决方案1】:
  1. filter 是函数指针,而不是 int 指针。
  2. 在您的代码中,filter 在本地范围内限定为 if else 块,这是错误的。

工作代码如下所示:

int nodots(const struct dirent *dp)
{
    return (dp->d_name[0] != '.');
}

int main(int argc, char **argv)
{
  struct dirent **entries;
  ...
  int (*myfilter)(const struct dirent *) = NULL;
  if(some_condition) myfilter = nodots;
  ...
  nents = scandir(".", &entries, myfilter, alphasort);
}

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    相关资源
    最近更新 更多