首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

fnmatch范例详解(与readdir、opendir实现模糊查询)

2012-09-23 
fnmatch实例详解(与readdir、opendir实现模糊查询)fnmatch:int fnmatch(const char *pattern, const char *

fnmatch实例详解(与readdir、opendir实现模糊查询)

fnmatch:int fnmatch(const char *pattern, const char *string, int flags);
man中是这么写道:The  fnmatch()  function checks whether the string argument matches the pattern argument, which is a shell wildcard pattern. 就是判断字符串是不是符合pattern所指的结构。  

FNM_NOESCAPE如果这个标志设置了,处理反斜杠为普通字符,而不是转义字符。FNM_PATHNAME如果这个标志设置了,string 里的斜杠只匹配 pattern 里的斜杠,它不能匹配星号(*)或问号(?)元字符,也不能匹配包含斜杠的中括号表达式([])。FNM_PERIOD如果这个标志设置了,string 里的起始点号必须匹配 pattern 里的点号。一个点号被认为是起始点号,如果它是string 第一个字符,或者如果同时设置了FNM_PATHNAME,紧跟在斜杠后面的点号。FNM_FILE_NAME这是 FNM_PATHNAME 的 GNU 同义语。FNM_LEADING_DIR如果这个标志(GNU 扩展)设置了,模式必须匹配跟随在斜杠之后的 string 的初始片断。这个标志主要是给 glibc 内部使用并且只在一定条件下实现。FNM_CASEFOLD如果这个标志(GNU 扩展)设置了,模式匹配忽略大小写。
返回值:0,string 匹配 pattern;FNM_NOMATCH,没有匹配;或者其它非零值,如果出错。

(程序来自网络)

#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]);//打开指定路径pattern = argv[1];//路径存在if(dir != NULL){//逐个获取文件夹中文件    while( (entry = readdir(dir)) != NULL){      ret = fnmatch(pattern, entry->d_name, FNM_PATHNAME|FNM_PERIOD);      if(ret == 0)//符合pattern的结构{        printf("%s\n", entry->d_name);      }else if(ret == FNM_NOMATCH){        continue ;      }else{        printf("error file=%s\n", entry->d_name);    }    }    closedir(dir);  }}


fnmatch范例详解(与readdir、opendir实现模糊查询)

 

 

 

热点排行