转自:http://www.zybang.com/question/62a9c6f4f875fc3cab6dead25a3a7ad8.html
英文原版地址:http://www.man7.org/linux/man-pages/man7/glob.7.html
个人观点:最近项目需要用到了模式匹配路径下的文件名的功能,网上的资料几乎都是一样的,还是看man手册里写的比较全面。
我使用了系统函数fnmatch,第三个参数写得是0, 实现了* ? 【】的模式匹配, 和正则表达式还差很多, 但是这个功能也比较不错了,
在网上找了源代码,有两份,一份是apple的,另一份是linux的。
apple源代码:http://www.man7.org/linux/man-pages/man3/glob.3.html
linux源代码详见coreutils-8.25/lib/fnmatch.c以下粘出部分代码:
int
fnmatch (const char *pattern, const char *string, int flags)
{
# if HANDLE_MULTIBYTE
# define ALLOCA_LIMIT 2000
if (__builtin_expect (MB_CUR_MAX, 1) != 1)
{
mbstate_t ps;
size_t patsize;
size_t strsize;
size_t totsize;
wchar_t *wpattern;
wchar_t *wstring;
int res;
/* Calculate the size needed to convert the strings to
wide characters. */
memset (&ps, '\0', sizeof (ps));
patsize = mbsrtowcs (NULL, &pattern, 0, &ps) + 1;
if (__builtin_expect (patsize != 0, 1))
{