[C Language] 利用正则表达式获取.cpp文件

EG: ./test_search /work/practice/test_createdir/  .cpp$
 

#include <stdio.h>
#include <sys/types.h>
#include <regex.h>

#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>

char file_name[255][255];
int file_num = 0;

int readFileList(char *basePath)

    DIR *dir;
    struct dirent *ptr;
    //char base[1000];
 //char *base;
    if ((dir=opendir(basePath)) == NULL)
    {
        perror("Open dir error...");
        exit(1);
    }

    while ((ptr=readdir(dir)) != NULL)
    {
        if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)    ///current dir OR parrent dir
            continue;
        else if(ptr->d_type == 8)    ///file
            {
    strcpy(file_name[file_num],ptr->d_name);
    file_num ++;
      printf("get the path == %s\n",ptr->d_name);
     }
        else
        {
     continue;
        }
    }
    closedir(dir);
    return file_num;
}

void search_pattern(char *file,char *arg)
{
 int status;
    int i;
    int cflags = REG_EXTENDED;
    regmatch_t pmatch[1];
    const size_t nmatch = 1;
    regex_t reg;
    //const char *pattern = "^[0-9]{5}\.mp4$";
 const char *pattern = arg;
    char *buf = file;

    regcomp(&reg, pattern, cflags);
    status = regexec(&reg, buf, nmatch, pmatch, 0);

    if (status == REG_NOMATCH){
        printf("No F**K!\n");
    } else if(status == 0){
        printf("F**K: \n");
        for(i = pmatch[0].rm_so; i < pmatch[0].rm_eo; ++i){
            putchar(buf[i]);
        }
        printf("\n");                                                                                                                                  
    }      
    regfree(&reg);
}

void
read_param(char *param1,char *param2)
{
 printf("get the params1 == %s,get the params2 ==%s\n",param1,param2);
 int num = readFileList(param1);
 char *buf;
 for(int i = 0; i< num;i++)
 {
  
  buf = file_name[i];
  printf("the get buf[%d] = %s\n",i,buf);
  search_pattern(file_name[i],param2);
 } 
}

int
main(int argc, char *argv[]){
 char *arg1 = argv[1];
 char *arg2 = argv[2];
 read_param(argv[1],argv[2]);
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值