scandir过滤子字符串

时间:2016-01-15 02:39:32

标签: c linux filter substring scandir

我正在尝试按子字符串过滤scandir。我的功能正常,但只是预定的字符串。

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

但我找不到可以过滤argv[i]的方法,因为我无法宣布它。

int (*filter)(const struct dirent *)

你们知道任何解决方案吗?

2 个答案:

答案 0 :(得分:0)

您可能必须使用全局变量,如果在线程环境或信号处理程序中使用,则会产生所有不良副作用:

static const char *global_filter_name;

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

并在致电global_filter_name之前设置scandir

答案 1 :(得分:0)

你的函数不会冒递归的风险,所以:

您可以将static-storage-duration或thread-storage-duration对象用于其他上下文:

/* At file scope */
static const char ** filter_names;

/* ... */

/*
 * Prior to being invoked, populate filter_names
 * with a pointer into an array of pointers to strings,
 * with a null pointer sentinel value at the end
 */
int nameFilter(const struct dirent *entry){
    const char ** filter;

    for (filter = filter_names; *filter; ++filter) {
        if(strstr(entry->d_name,*filter) != NULL)
            return 1;
      }
    /* chqrlie correction */
    return 0;
}
相关问题