现在的位置: 首页 > 综合 > 正文

linux c中用匹配符搜索文件

2013年10月01日 ⁄ 综合 ⁄ 共 726字 ⁄ 字号 评论关闭

在linux编程中,有时候会用到批量处理文件。比如写一个上传工具,用户输入文件名,如果此时用户使用的是匹配的文件名,那么程序应该做到根据匹配字符串自动搜索符合要求的文件名的功能。

linux有一个glob函数,可以做到这一点,该函数位于头文件glob.h中

事例:

#include <iostream>

#include <string>

#include <glob.h>

using namespace std;

 

void print_gl(glob_t &gl)

{

        for(int i=0;i<gl.gl_pathc;i++)

        {

                cout<<gl.gl_pathv[i]<<endl;

         }

}

 

void test_glob(int argc , char **argv)

{

         glob_t gl;

         for(int i=1;i<argc;i++)

         {

                gl.gl_offs=0;

                glob(argv[i],GLOB_TILDE,0,&gl);

                print_gl(gl);

                globfree(&gl);

         }

 }

 

int main(int argc,char **argv)

{

        if(argc<2)

        {

               cout<<"<file name>"<<endl;

               return 0;

         }

 

         test_glob(argc,argv);

         return 0;

}

 

抱歉!评论已关闭.