readdir
是一个用于读取目录内容的函数,通常在 C 语言中使用。要使用 readdir
实现文件搜索,你需要遵循以下步骤:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
DIR *dir = opendir("path/to/directory");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
readdir
读取目录中的文件和子目录:struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 处理每个条目
}
char search_string[] = "example";
if (strstr(entry->d_name, search_string) != NULL) {
printf("Found: %s\n", entry->d_name);
}
closedir(dir);
将以上代码片段组合在一起,你可以创建一个简单的文件搜索程序。下面是一个完整的示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return EXIT_FAILURE;
}
const char *path = argv[1];
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
struct dirent *entry;
char search_string[] = "example";
while ((entry = readdir(dir)) != NULL) {
if (strstr(entry->d_name, search_string) != NULL) {
printf("Found: %s\n", entry->d_name);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
编译并运行此程序,传入要搜索的目录路径作为参数。程序将输出包含 “example” 字符串的所有文件和子目录。