在 Debian 中,readdir 是一个用于读取目录内容的函数
libc6-dev 包。在终端中运行以下命令:sudo apt-get update
sudo apt-get install libc6-dev
readdir_regex.c,并添加以下代码:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <regex.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <directory> <regex_pattern>\n", argv[0]);
return 1;
}
const char *dir = argv[1];
const char *pattern = argv[2];
DIR *dp = opendir(dir);
if (!dp) {
perror("opendir");
return 1;
}
struct dirent *entry;
regex_t regex;
int reti;
reti = regcomp(®ex, pattern, REG_EXTENDED);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
return 1;
}
while ((entry = readdir(dp)) != NULL) {
if (regexec(®ex, entry->d_name, 0, NULL, 0) == 0) {
printf("%s\n", entry->d_name);
}
}
regfree(®ex);
closedir(dp);
return 0;
}
这个程序接受两个命令行参数:一个目录和一个正则表达式模式。它将打开目录,读取其中的条目,并使用正则表达式匹配来打印匹配的文件名。
gcc -o readdir_regex readdir_regex.c
./readdir_regex <directory> <regex_pattern>
将 <directory> 替换为您要读取的目录,将 <regex_pattern> 替换为您要使用的正则表达式模式。
例如:
./readdir_regex /home/user/Documents ".*\.txt"
这将列出 /home/user/Documents 目录中所有以 .txt 结尾的文件。