konstant
konstant

Reputation: 705

scandir in c - sel function implementation

man scandir gives me a following structure of the scandir function:

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

Suppose I define the following:

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

this lists all the files and folder names in the current folder. But suppose I have a filter and compar function of the following structure:

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

and similar for compar, and I want to call this filter function or just NULL based on some criteria:

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

but this gives pointer error. Is there a way to fix this?

Upvotes: 0

Views: 489

Answers (1)

mnistic
mnistic

Reputation: 11020

  1. filter is a function pointer, not an int pointer.
  2. In your code, filter is locally scoped to the if else block, which is wrong.

Working code would look something like:

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

Upvotes: 1

Related Questions