下面这个例子用fnmatch函数进行字符通配,比如匹配*、?等字符。
源代码是:
编译并运行此程序:
gcc -Wall fnmatch.c
./a.out "*.c" /src/mycode/c
此命令将把/src/mycode/c目录下*.c文件显示出来。即匹配文件名为*.c的
源代码是:
/************关于本文档******************************************** *filename: fnmatch.c *purpose: 说明用fnmatch进行字符匹配的方法 *wrote by: zhoulifa(zhoulifa@163.com) 周立发(http://zhoulifa.bokee.com) Linux爱好者 Linux知识传播者 SOHO族 开发者 最擅长C语言 *date time:2008-01-27 20:33 上海大雪天,据说是多年不遇 *Note: 任何人可以任意复制代码并运用这些文档,当然包括你的商业用途 * 但请遵循GPL *Thanks to: * Ubuntu 本程序在Ubuntu 7.10系统上测试完全正常 * Google.com 我通常通过google搜索发现许多有用的资料 *Hope:希望越来越多的人贡献自己的力量,为科学技术发展出力 * 科技站在巨人的肩膀上进步更快!感谢有开源前辈的贡献! *********************************************************************/ #include <locale.h> #include <fnmatch.h> #include <stdio.h> #include <sys/types.h> #include <dirent.h> main(int argc, char *argv[] ) { char *pattern; DIR *dir; struct dirent *entry; int ret; /*setlocale(LC_ALL, "zh_CN.UTF-8");*/ dir = opendir(argv[2]); pattern = argv[1]; if(dir != NULL){ while( (entry = readdir(dir)) != NULL){ ret = fnmatch(pattern, entry->d_name, FNM_PATHNAME|FNM_PERIOD); if(ret == 0){ printf("%s/n", entry->d_name); }else if(ret == FNM_NOMATCH){ continue ; }else{ printf("error file=%s/n", entry->d_name); } } closedir(dir); } } |
gcc -Wall fnmatch.c
./a.out "*.c" /src/mycode/c
此命令将把/src/mycode/c目录下*.c文件显示出来。即匹配文件名为*.c的