c语言模式匹配路径

引言

在Linux 的日常操作中, 经常需要找某个路径下的某个文件夹/文件, 这都是日常操作, 而且是很简单的, find 命令能够完美的搞定!可是如果用C语言怎么实现呢?

glob

英文语言说明

SYNOPSIS
       #include <glob.h>

       int glob(const char *pattern, int flags,
                int (*errfunc) (const char *epath, int eerrno),
                glob_t *pglob);
       void globfree(glob_t *pglob);

DESCRIPTION
       The glob() function searches for all the pathnames matching pattern according to the rules used by the shell (see glob(7)).
       No tilde expansion or parameter substitution is done; if you want these, use wordexp(3).

       The globfree() function frees the dynamically allocated storage from an earlier call to glob().

       The results of a glob() call are stored in the structure pointed to by pglob.  This structure is of type  glob_t  (declared
       in <glob.h>) and includes the following elements defined by POSIX.2 (more may be present as an extension):

           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;

       Results are stored in dynamically allocated storage.

       The argument flags is made up of the bitwise OR of zero or more the following symbolic constants, which modify the behavior
       of glob():
       GLOB_ERR
              Return upon a read error (because a directory does not have read  permission,  for  example).   By  default,  glob()
              attempts carry on despite errors, reading all of the directories that it can.

       GLOB_MARK
              Append a slash to each path which corresponds to a directory.

       GLOB_NOSORT
              Don't sort the returned pathnames.  The only reason to do this is to save processing time.  By default, the returned
              pathnames are sorted.

       GLOB_DOOFFS
              Reserve pglob->gl_offs slots at the beginning of the list of strings in pglob->pathv.  The  reserved  slots  contain
              null pointers.

       GLOB_NOCHECK
              If  no  pattern  matches,  return  the  original  pattern.   By default, glob() returns GLOB_NOMATCH if there are no
              matches.

       GLOB_APPEND
              Append the results of this call to the vector of results returned by a previous call to glob().   Do  not  set  this
              flag on the first invocation of glob().

       GLOB_NOESCAPE
              Don't  allow backslash ('\') to be used as an escape character.  Normally, a backslash can be used to quote the fol-
              lowing character, providing a mechanism to turn off the special meaning metacharacters.

       flags may also include any of the following, which are GNU extensions and not defined by POSIX.2:

       GLOB_PERIOD
              Allow a leading period to be matched by metacharacters.  By default, metacharacters can't match a leading period.

       GLOB_ALTDIRFUNC
              Use  alternative  functions   pglob->gl_closedir,   pglob->gl_readdir,   pglob->gl_opendir,   pglob->gl_lstat,   and
              pglob->gl_stat for filesystem access instead of the normal library functions.

       GLOB_BRACE
              Expand csh(1) style brace expressions of the form {a,b}.  Brace expressions can be nested.  Thus, for example, spec-
              ifying the pattern "{foo/{,cat,dog},bar}" would return the same results as four  separate  glob()  calls  using  the
              strings: "foo/", "foo/cat", "foo/dog", and "bar".

       GLOB_NOMAGIC
              If the pattern contains no metacharacters, then it should be returned as the sole matching word, even if there is no
              file with that name.

       GLOB_TILDE
              Carry out tilde expansion.  If a tilde ('~') is the only character in the pattern, or an initial tilde  is  followed
              immediately  by  a  slash  ('/'), then the home directory of the caller is substituted for the tilde.  If an initial
              tilde is followed by a username (e.g., "~andrea/bin"), then the tilde and  username  are  substituted  by  the  home
              directory  of  that user.  If the username is invalid, or the home directory cannot be determined, then no substitu-
              tion is performed.
       GLOB_TILDE_CHECK
              This provides behavior similar to that of GLOB_TILDE.  The difference is that if the username  is  invalid,  or  the
              home  directory  cannot  be  determined,  then  instead  of  using  the  pattern  itself as the name, glob() returns
              GLOB_NOMATCH to indicate an error.

       GLOB_ONLYDIR
              This is a hint to glob() that the caller is interested only in directories that match the pattern.  If the implemen-
              tation can easily determine file-type information, then nondirectory files are not returned to the caller.  However,
              the caller must still check that returned files are directories.  (The purpose of this flag is  merely  to  optimize
              performance when the caller is interested only in directories.)

       If errfunc is not NULL, it will be called in case of an error with the arguments epath, a pointer to the path which failed,
       and eerrno, the value of errno as returned from one of the calls to opendir(3), readdir(3), or stat(2).  If errfunc returns
       nonzero, or if GLOB_ERR is set, glob() will terminate after the call to errfunc.

       Upon  successful return, pglob->gl_pathc contains the number of matched pathnames and pglob->gl_pathv contains a pointer to
       the list of pointers to matched pathnames.  The list of pointers is terminated by a null pointer.

       It is possible to call glob() several times.  In that case, the GLOB_APPEND flag has to be set in flags on the  second  and
       later invocations.

       As a GNU extension, pglob->gl_flags is set to the flags specified, ored with GLOB_MAGCHAR if any metacharacters were found.


example

首先看真是的结果:

#include<stdio.h>
#include<stdlib.h>
#include<glob.h>

int main() 
{
	glob_t globObj;
        int rst = glob("/usr/g/sdc_image_pool/imag*/*/*/*/stage", GLOB_MARK|GLOB_NOCHECK, NULL, &globObj);
        if (rst != 0) {
            perror(": glob execute failed:");
            return -1;
        }   
/*
           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;
*/

        int i = 0;
        for (i = 0; i < globObj.gl_pathc; ++i) {
	    printf("%s\n", globObj.gl_pathv[i]);	
        }   

        globfree(&globObj);        
	return 1;
}

运行结果:

 

注意:

根据我的实践, /usr/g/sdc_image_pool/imag*/*/*/*/stage     能匹配出来

                          /usr/g/sdc_image_pool/images/*/*/*/stage   可以匹配出来

                          /usr/g/sdc_image_pool/images/*/stage        匹配不出来

并不能完美的实现find的功能, 有知道怎么实现的朋友还望不吝赐教!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值