首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >scandir匹配函数参数

scandir匹配函数参数
EN

Stack Overflow用户
提问于 2011-07-15 08:20:35
回答 4查看 2.7K关注 0票数 2

我使用scandir来匹配目录中的某些文件。match函数接受const struct dirent *dp参数。

但我还需要传递另一个参数。当我尝试这样做时,编译给我一个警告(而不是错误),我的匹配函数是不兼容的指针类型。

不允许传递另一个参数来匹配函数吗?如果不是,我可能不得不将这个特定的变量设为全局变量,这是我不想做的。

代码片段:

代码语言:javascript
复制
/* below I am adding new argument - char *str */
match_function (const struct dirent *dp, char *str) {
}

function() {
count = scandir(PATH, &namelist, match_function, alphasort);
}

警告:

代码语言:javascript
复制
warning: passing argument 3 of 'scandir' from incompatible pointer type
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-07-15 10:34:41

另一种方法可能比使用全局变量或特定于线程的数据更可取,它只是编写您自己的scandir替代品,并让它接受一个额外的void *参数,该参数将传递给match函数。考虑到scandir很容易在不到50行的代码中实现,这是完全合理的。

下面是scandir的一个可能的实现

http://git.etalabs.net/cgi-bin/gitweb.cgi?p=musl;a=blob;f=src/dirent/scandir.c

票数 2
EN

Stack Overflow用户

发布于 2011-07-15 10:30:06

唯一可移植且线程/库安全的方法是使用特定于POSIX线程的数据。

代码语言:javascript
复制
static pthread_key_t key;
static pthread_once_t init = PTHREAD_ONCE_INIT;
static void initfunc()
{
    int r = pthread_key_create(&key);
    assert(r==0);
}

match_function (const struct dirent *dp)
{
    char *str = pthread_getspecific(key);
    /* ... */
}

function() {
    pthread_once(&init, initfunc);
    pthread_setspecific(key, str);
    count = scandir(PATH, &namelist, match_function, alphasort);
}
票数 2
EN

Stack Overflow用户

发布于 2011-07-15 11:42:24

明确回答你的问题

不允许传递另一个参数来匹配函数吗?

不是的。scandir()的作者指定了它所期望的match函数的类型;作为scandir()的用户,您必须遵循该规范,或者编写您自己的scandir()-equivalent,按照R..的建议以您想要的方式执行操作。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6701461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档