温馨提示×

使用copendir实现文件搜索功能

小樊
41
2025-11-03 05:58:05
栏目: 编程语言

copendir 是一个用于打开目录的函数,通常与 readdir 一起使用来遍历目录中的文件和子目录。以下是一个简单的示例,展示了如何使用 copendirreaddir 实现文件搜索功能:

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

void search_files(const char *path, const char *filename) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;

    if (!(dir = opendir(path))) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

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

        if (lstat(path_buf, &statbuf) == -1) {
            perror("lstat");
            continue;
        }

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

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <directory> <filename>\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 filename_to_find

请注意,这个示例程序没有处理符号链接和其他可能的错误情况。在实际应用中,你可能需要根据具体需求对其进行修改和扩展。

0