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(®, pattern, cflags);
status = regexec(®, 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(®);
}
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;
}