linux

如何用copendir实现文件搜索

小樊
43
2025-07-30 11:18:08
栏目: 编程语言

opendir 是一个用于打开目录的函数,通常与 readdir 函数一起使用来遍历目录中的文件和子目录。以下是一个使用 opendirreaddir 实现简单文件搜索的示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

void search_files(const char *path, const char *search_term) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;
    char full_path[PATH_MAX];

    if (!(dir = opendir(path))) {
        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 (stat(full_path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            search_files(full_path, search_term);
        } else if (strstr(entry->d_name, search_term) != NULL) {
            printf("Found: %s\n", full_path);
        }
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <path> <search_term>\n", argv[0]);
        return 1;
    }

    search_files(argv[1], argv[2]);

    return 0;
}

这个程序接受两个命令行参数:要搜索的目录路径和要搜索的文件名(或文件名的一部分)。它会递归地遍历目录及其子目录,并打印出包含搜索词的文件路径。

要编译并运行此程序,请将其保存为 search_files.c,然后使用以下命令:

gcc search_files.c -o search_files
./search_files /path/to/search "search_term"

/path/to/search 替换为要搜索的目录路径,将 "search_term" 替换为要搜索的文件名或文件名的一部分。

0
看了该问题的人还看了