c - 使用 c REGEX 表达式列出和过滤文件

标签 c regex file

在下面的代码中,我尝试仅使用正则表达式过滤掉名为 test.jpg 的文件,我做错了什么,因为下面的代码没有过滤掉这个文件?

我知道有更简单的方法,但最终我想将正则表达式更改为 ^(image_)\\d{3,6}_201412\\d{2}_\\d{6}\\.(jpg) 而且我的文件夹包含 100,000 多个文件,所以我只能使用 c getdents 函数,与任何其他方式相比,它都非常快

我得到以下输出:

**************found*******

image_0179_20141212_060714.jpg

#define _GNU_SOURCE
#include <dirent.h>     /* Defines DT_* constants */
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <string.h>
#include <regex.h>
#include <stdio.h>

#define handle_error(msg) \
       do { perror(msg); exit(EXIT_FAILURE); } while (0)

struct linux_dirent {
    long           d_ino;
    off_t          d_off;
    unsigned short d_reclen;
    char           d_name[];
};

#define BUF_SIZE 1024*1024*5

int
main(int argc, char *argv[])
{
    int fd, nread;
    char buf[BUF_SIZE];
    struct linux_dirent *d;
    int bpos;
    char d_type;
    regex_t reg;
    regmatch_t pmatch[40];
    #define NAME "image_0179_20141212_060714.jpg"
    const char *pattern = "^(image_)\\d{3,6}_201412\\d{2}_\\d{6}\\.(jpg)";
    regcomp(&reg, pattern, REG_ICASE | REG_EXTENDED);
    int retval = 0;
    char buffer[1024] = "";
    fd = open(argc > 1 ? argv[1] : ".", O_RDONLY | O_DIRECTORY);
    if (fd == -1)
         handle_error("open");
    for ( ; ; )
    {
       nread = syscall(SYS_getdents, fd, buf, BUF_SIZE);
       if (nread == -1)
         handle_error("getdents");
       if (nread == 0)
          break;
       for (bpos = 0; bpos < nread;)
       {
           d = (struct linux_dirent *) (buf + bpos);
           d_type = *(buf + bpos + d->d_reclen - 1);
           if( d->d_ino != 0 && d_type == DT_REG )
           {
                //printf("%s\n", (char *)d->d_name );
                if (strstr(d->d_name, NAME) != NULL)
                {
                    printf("**************found*******\n");
                    printf("%s\n", (char *)d->d_name );
                };

                retval = regexec(&reg, d->d_name, 2, pmatch, 0);
                //printf("%d\n",retval);
                if(retval==0)
                {
                    printf("**************found regex*******\n");
                    printf("%s\n", (char *)d->d_name );
                }
            }
            bpos += d->d_reclen;
        }
     }
     regfree(&reg);
     exit(EXIT_SUCCESS);
}

最佳答案

改用下面的正则表达式

^image_[0-9]{3,6}_201412[0-9]{2}_[0-9]{6}\.jpg$

关于c - 使用 c REGEX 表达式列出和过滤文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56816531/

相关文章:

regex - 使用正则表达式查找不在两个字符之间的文本

c - write() 在两种情况下表现不同

c++ - 一次从 .txt 文件读取两行 - C++ getline/streams?

c++ - 使用 C++ 读取配置文件

C: Xcode 和 VS2015 中的复数

c - 获取实验变量时使用变量

c - 这段 C 代码的目的是什么?

C - 将一个数字的奇数位添加到另一个数字的末尾

regex - 使用 Regex.fromLiteral() 创建的 Regex 到底匹配什么?

java - 如何在java中的字符串的某些部分使用正则表达式?