我使用scandir来匹配目录中的某些文件。match函数接受const struct dirent *dp参数。
但我还需要传递另一个参数。当我尝试这样做时,编译给我一个警告(而不是错误),我的匹配函数是不兼容的指针类型。
不允许传递另一个参数来匹配函数吗?如果不是,我可能不得不将这个特定的变量设为全局变量,这是我不想做的。
代码片段:
/* below I am adding new argument - char *str */
match_function (const struct dirent *dp, char *str) {
}
function() {
count = scandir(PATH, &namelist, match_function, alphasort);
}警告:
warning: passing argument 3 of 'scandir' from incompatible pointer type发布于 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
发布于 2011-07-15 10:30:06
唯一可移植且线程/库安全的方法是使用特定于POSIX线程的数据。
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);
}发布于 2011-07-15 11:42:24
明确回答你的问题
不允许传递另一个参数来匹配函数吗?
不是的。scandir()的作者指定了它所期望的match函数的类型;作为scandir()的用户,您必须遵循该规范,或者编写您自己的scandir()-equivalent,按照R..的建议以您想要的方式执行操作。
https://stackoverflow.com/questions/6701461
复制相似问题