3.1.5 glob

包含的头文件

#include <glob.h>

glob函数

/****************************
 *功能:通过通配符pattern找到pathname
 *参数:pattern通配符
 *      flags:常用的特殊要求
 *      函数指针:类型int (const char *epath,int errno)返回出错的路径和原因,不需要此功能则需要NULL
 *      pglob:解析pattern结果存放到glob_t的结构体类型
 * *************************/
int glob(const char *pattern , int flags , int (*errfunc)(const char *epath,int errno),glob_t *pglob);

/***********************************
 *gl_pathc:匹配pathname的个数
 *gl_pathv:匹配pathname的列表
 * ********************************/
typedef struct {
    size_t   gl_pathc;    /* Count of paths matched so far  */
    char   **gl_pathv;    /* List of matched pathnames.  */
    size_t   gl_offs;     /* Slots to reserve in gl_pathv.  */
} glob_t;

/****************************
 *功能:释放空间
 *************************/
void globfree(glob_t *pglob);

例子:

/*********************************
 * 查看/etc/目录下以a*.config的文件个数
 ********************************/
#include <stdio.h>
#include <stdlib.h>
#include <glob.h>

#define PAT "/etc/a*.conf"
//#define   PAT "/etc/*"

/*解析失败的原因*/
static int errfunc_(const char *errpath , int errno)
{
    puts(errpath);
    fprintf(stderr , "ERR MSG :" , strerror(errno));
    return 0 ;
}

int main(int argc ,char **argv)
{
    //1.定义
    glob_t globres ;
    int err ;
    int i ;
    //2.查看
    err = glob(PAT, 0 ,NULL, &globres);
    if(err)
    {
        printf("Error Code = %d\n",err);
        exit(1);
    }
    //3.输出
    for(i = 0 ; i < globres.gl_pathc ; i++)
        puts(globres.gl_pathv[i]);
    //4.释放
    globfree(&globres);
    exit(0);
}

 

posted @ 2016-03-15 14:44  muzihuan  阅读(312)  评论(0编辑  收藏  举报