centos

如何利用CentOS readdir实现文件搜索功能

小樊
34
2025-10-02 23:07:50
栏目: 智能运维

在 CentOS 系统中,readdir 是一个用于读取目录内容的函数,通常在 C 语言编程中使用。如果你想使用 readdir 实现文件搜索功能,可以编写一个简单的 C 程序来遍历目录并查找特定文件或文件类型。以下是一个基本的示例程序,演示如何使用 readdir 来搜索目录中的文件:

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

void search_directory(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 fullpath[1024];
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        // 获取文件信息
        if (stat(fullpath, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        // 检查是否是目录,如果是则递归搜索
        if (S_ISDIR(statbuf.st_mode)) {
            search_directory(fullpath, filename);
        } else {
            // 检查文件名是否匹配
            if (strstr(entry->d_name, filename) != NULL) {
                printf("Found: %s\n", fullpath);
            }
        }
    }

    // 关闭目录
    closedir(dir);
}

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

    const char *directory = argv[1];
    const char *filename_pattern = argv[2];

    search_directory(directory, filename_pattern);

    return EXIT_SUCCESS;
}

编译和运行

  1. 将上述代码保存到一个文件中,例如 search.c

  2. 使用以下命令编译程序:

    gcc -o search search.c
    
  3. 运行程序并指定要搜索的目录和文件名模式:

    ./search /path/to/search "pattern"
    

说明

这个程序会递归地搜索指定目录及其子目录中的所有文件,并打印出匹配指定模式的文件路径。你可以根据需要修改 filename_pattern 来搜索特定的文件名或文件类型。

0
看了该问题的人还看了