在C语言开发中,借助readdir函数可遍历目录内容并以此为基础实现文件搜索功能。具体实现步骤如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
void search_files(const char *path, const char *filename_pattern) {
DIR *dir;
struct dirent *entry;
char full_path[PATH_MAX];
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (entry->d_type == DT_DIR) {
search_files(full_path, filename_pattern);
} else {
if (strstr(entry->d_name, filename_pattern) != NULL) {
printf("Found: %sn", full_path);
}
}
}
closedir(dir);
}
search_files 函数,传入要搜索的目录路径和文件名模式:int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <directory> <filename_pattern>n", argv[0]);
return 1;
}
search_files(argv[1], argv[2]);
return 0;
}
现在,你可以编译并运行这个程序,传入要搜索的目录路径和文件名模式。例如:
gcc search_files.c -o search_files
./search_files /path/to/search ".*.txt"
通过上述步骤,即可利用 readdir 实现递归文件搜索;编译后执行示例命令,程序将遍历指定目录及其子目录,输出所有匹配 .txt 模式的文件完整路径。