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所指的结构。
(程序来自网络)
#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); }}