Search code examples
clinuxfiltersubstringscandir

scandir filter by substring


I am trying to filter a scandir by substrings. I have my function working but just with a predetermined string.

int nameFilter(const struct dirent *entry) {
    if (strstr(entry->d_name, "example") != NULL)
        return 1;
    return 0;
}

But I can't find a way where I can filter an argv[i] because there is no way I can declare it.

int (*filter)(const struct dirent *)

Do you guys know any solution?


Solution

  • You may have to use a global variable, with all bad side-effects if used in a threaded environment or from a signal handler:

    static const char *global_filter_name;
    
    int nameFilter(const struct dirent *entry) {
        return strstr(entry->d_name, global_filter_name) != NULL;
    }
    

    and set global_filter_name before calling scandir.