Filtering scandir for filenames in folder C Language

Antonio Falcone picture Antonio Falcone · Jul 12, 2013 · Viewed 7.2k times · Source

I am using scandir() function in C, on a folder where i need to get files whose filenames are exactly = "exe".

How can i filter the entries returned by scandir?

Third argument of scandir is filter:

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

could it be useful for my purpose?

Answer

tuckermi picture tuckermi · Jul 12, 2013

Yes, the filter argument is a function pointer that lets you pass in a function to filter the results. You might want to write a function like the one below and pass it by name as the value for filter.

int file_select(const struct dirent *entry)
{
   return strcmp(entry->d_name, "exe");
}