scandir 匹配函数参数
我正在使用 scandir 来匹配目录中的某些文件。 match 函数采用 const struct dirent *dp 参数。
但我还需要通过它传递另一个参数。当我尝试这样做时,编译会发出警告(不是错误),指出我的匹配函数的指针类型不兼容。
是否不允许向 match 函数传递另一个参数?如果不是,我可能必须将该特定变量设置为全局变量,但我不想这样做。
代码片段:
/* 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
I am using scandir to match certain files from a dir. The match function takes const struct dirent *dp
argument.
But I also need to pass another argument with it. When I try to do that, compiles gives me a warning (not error) that my match function is of incompatible pointer type.
Is it not allowed to pass another argument to match function? If it's not, I might have to make that particular variable global which I do not want to do.
code snippet:
/* 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:
warning: passing argument 3 of 'scandir' from incompatible pointer type
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
另一种方法可能比使用全局变量或线程特定数据更好,就是编写您自己的 scandir 替代品,并让它采用额外的 void * 参数它将传递给 match 函数。考虑到
scandir
可以用不到 50 行代码轻松实现,这是完全合理的。以下是
scandir
的可能实现:http://git.etalabs.net/cgi-bin/gitweb.cgi?p=musl;a=blob;f=src/dirent/scandir.c
Another approach, which may be preferable to using global variables or thread-specific data, is just to write your own replacement for
scandir
and have it take an extravoid *
argument which it would pass to the match function. Considering thatscandir
is easily implemented in less than 50 lines of code, this is perfectly reasonable.Here is a possible implementation of
scandir
:http://git.etalabs.net/cgi-bin/gitweb.cgi?p=musl;a=blob;f=src/dirent/scandir.c
执行您想要的操作的唯一可移植且线程/库安全的方法是使用 POSIX 线程特定数据。
如果您不关心线程安全,您可以为
str
使用全局变量,这样会更容易。The only portable and thread/library-safe way to do what you want is with POSIX thread-specific data.
If you don't care about thread-safety you can just use a global variable for
str
and make it a lot easier.明确回答你的问题
不。
scandir()
的作者指定了它需要什么类型的match
函数;作为scandir()
的用户,您必须遵循该规范,或者编写您自己的scandir()
等效项,按照您想要的方式执行操作,如 R..。To explicitly answer your question
No. The author of
scandir()
specified what type ofmatch
function it expects; as the user ofscandir()
you must follow that specification, or write your ownscandir()
-equivalent that does things the way you want as suggested by R...想一想:如何将附加参数传递给它?您可能正在寻找的是一个闭包,尽管
gcc
显然能够通过 嵌套函数。Think about it: how would you pass the additional parameter to it? What you're probably looking for is a closure, which isn't supported by the C standard yet although
gcc
apparently has the ability to do it via nested functions.