用fnmatch函数进行字符通配

应一些朋友的要求,我把我电脑上的源代码全部张贴到这里。当然稍微做些说明。
这样有个好处就是我自己可以通过google随时搜索源代码例子,比如我想找udp编程的例子时,我就在google里输入:udp site:zhoulifa.bokee.com搜索,能看到我自己的源代码例子。

下面这个例子用fnmatch函数进行字符通配,比如匹配*、?等字符。

/************关于本文档********************************************
*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:希望越来越多的人贡献自己的力量,为科学技术发展出力
* 科技站在巨人的肩膀上进步更快!感谢有开源前辈的贡献!

添加注释: wenhao
编译方式: gcc fnmatch.c -o fnmatch -Wall
输入指令: ./fnmatch "*.c" .
********************************************************************
*/
#include <locale.h>
#include <fnmatch.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char *argv[])
{
char *pattern;
DIR *dir;
struct dirent *entry;
int ret;

dir = opendir(argv[2]); //打开argv[2]文件夹
pattern = argv[1]; //将argv[1]测试条件放在pattern中.

printf("the str is %s\n",pattern);

if(dir != NULL)
{
while( (entry = readdir(dir)) != NULL)//判断是否将本文件夹内容读完
{

ret = fnmatch(pattern, entry->d_name, FNM_PATHNAME|FNM_PERIOD);//匹配成功返回0
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);//关闭打开的文件夹
}

return 0;
}


转自:http://zhoulifa.bokee.com/6614603.html

原文地址:https://www.cnblogs.com/hnrainll/p/2222742.html