linux

如何使用readdir实现文件搜索

小樊
43
2025-06-05 23:55:10
栏目: 编程语言

readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要使用 readdir 实现文件搜索,你需要遵循以下步骤:

  1. 包含必要的头文件:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
  1. 编写一个递归函数,该函数接受一个目录路径作为参数,并使用 opendirreaddirclosedir 函数来遍历目录及其子目录:
void search_files(const char *path) {
    DIR *dir;
    struct dirent *entry;

    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;
        }

        char full_path[1024];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        if (entry->d_type == DT_DIR) {
            search_files(full_path);
        } else {
            printf("%s\n", full_path);
        }
    }

    closedir(dir);
}
  1. main 函数中调用 search_files 函数,传入要搜索的目录路径:
int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <directory_path>\n", argv[0]);
        return 1;
    }

    search_files(argv[1]);

    return 0;
}
  1. 编译并运行程序:
gcc file_search.c -o file_search
./file_search /path/to/search

这将输出指定目录及其子目录中的所有文件。你可以根据需要修改 search_files 函数,例如添加文件名匹配条件以仅搜索特定类型的文件。

0
看了该问题的人还看了