【问题标题】:scandir filter by substringscandir 按子字符串过滤
【发布时间】:2016-01-15 02:39:31
【问题描述】:

我正在尝试通过子字符串过滤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 *)

你们知道有什么解决办法吗?

【问题讨论】:

标签: c linux filter substring scandir


【解决方案1】:

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

static const char *global_filter_name;

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

并在调用scandir之前设置global_filter_name

【讨论】:

【解决方案2】:

你的函数没有递归的风险,所以:

您可以使用 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;
}

【讨论】:

  • 我明白你做了什么。无论如何,我只需要一个argv[] 参数,但这肯定会起作用。谢谢。
  • return 0;移出for循环体。
猜你喜欢
  • 1970-01-01
  • 2013-12-22
  • 1970-01-01
  • 2012-07-06
  • 2020-06-07
  • 2011-08-14
相关资源
最近更新 更多