在Linux中,readdir
函数用于读取目录中的条目。要使用readdir
实现文件搜索,你需要遵循以下步骤:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return 1;
}
readdir
函数读取目录中的条目:struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 处理目录条目
}
entry->d_name
获取文件名,并根据需要进行搜索:char search_name[] = "target_file"; // 要搜索的文件名
if (strcmp(entry->d_name, search_name) == 0) {
printf("找到文件: %s\n", entry->d_name);
}
closedir(dir);
将以上代码片段组合在一起,你可以创建一个简单的文件搜索程序。以下是一个完整的示例:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("用法: %s <目录路径>\n", argv[0]);
return 1;
}
const char *path = argv[1];
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
char search_name[] = "target_file"; // 要搜索的文件名
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, search_name) == 0) {
printf("找到文件: %s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
编译并运行此程序,传入要搜索的目录路径作为参数。程序将输出找到的目标文件名。注意,这个示例仅搜索指定目录下的一个文件。如果你需要递归搜索整个目录树,你需要编写一个递归函数来遍历所有子目录。