我怎么能在参数选择SCANDIR功能 [英] how can I parameterize select function in scandir

查看:132
本文介绍了我怎么能在参数选择SCANDIR功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该SCANDIR()函数扫描目录dir,呼吁
选择()上的每个目录项为INT(*过滤器)(常量结构的dirent *)
在过滤器中使用如何传递模式值作为参数的fnmatch(为const char *模式,为const char *字符串,整数标志)的功能?

The scandir() function scans the directory dir, calling select() on each directory entry as "int(*filter)(const struct dirent *)" How can I pass pattern value as parameter to fnmatch(const char *pattern, const char *string, int flags) function used in filter ?

下面我的示例code

Here my sample code

int my_selectgrf(const struct dirent *namelist)
{
   int  r = 0;
   char     my_pattern[] = "*.grf";
   r = fnmatch(my_pattern, namelist->d_name, FNM_PERIOD);

   return (r==0)?1:0;
}
scandir("/pub/data/grf", &namelist, my_selectgrf, alphasort);

我的目标是能够使用my_pattern作为输入参数。

my goal is to be able to use my_pattern as input parameter.

推荐答案

答案很简单:你不能。这是一个残暴恶劣的API,它是彻底的可耻这样的事情被添加到POSIX最近在2008年(基于glibc的一个不好的设计)。这种API的没有办法参数,或通过它的上下文应该已经超过20年前废除了。

The short answer: You can't. This is an atrociously bad API, and it's outright shameful that something like this was added to POSIX as recently as 2008 (based on a bad design in glibc). This kind of API without a way to parameterize it or pass it a context should have been abolished 20+ years ago.

随着中说,有一些解决方法:

With that said, there are some workarounds:

方法1:使用全局变量,如果你的code需要是线程安全的,确保只有一个线程可以使用 SCANDIR 与给定同时扫描功能,通过锁定。这当然的连载的使用情况,如果你真的想被调用多个线程,其功能可能是不能接受的。

Approach 1: Use a global variable, and if your code needs to be thread-safe, ensure that only one thread can be using scandir with the given scan function at a time, by locking. This of course serializes usage, which is probably not acceptable if you actually want to be calling the function from multiple threads.

方法二:使用线程本地存储,无论是海湾合作委员会 __线程关键字(或C11 _Thread_local 关键字,这GCC可悲的是仍然不接受)或POSIX pthread_setspecific 和家人。这还算干净,但不幸的是它可能不正确;如果 SCANDIR 实施内部使用多线程,则参数可能无法在一些调用可用回扫描功能。在present,我不相信也有 SCANDIR 多线程的实现。

Approach 2: Use thread-local storage, either the GCC __thread keyword (or the C11 _Thread_local keyword, which GCC sadly still does not accept) or POSIX pthread_setspecific and family. This is fairly clean, but unfortunately it may not be correct; if the implementation of scandir internally used multiple threads, the parameter could fail to be available in some calls back to the scan function. At present, I don't believe there are multi-threaded implementations of scandir.

现在,更好的解决办法:

Now, the better solution:

SCANDIR ,写自己的函数做同样的事情,用正确的API。这是只有几行呢。

Ditch scandir and write your own function to do the same thing, with the proper API. It's only a few lines anyway.

这篇关于我怎么能在参数选择SCANDIR功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆