debian

Debian readdir如何处理子目录

小樊
31
2025-03-02 10:56:38
栏目: 智能运维

在Debian系统中,readdir函数用于读取目录中的条目。当使用readdir处理子目录时,需要递归地遍历目录结构。以下是一个简单的示例,展示了如何使用readdir处理子目录:

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

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

    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 (lstat(full_path, &statbuf) == -1) {
            perror("lstat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            printf("Directory: %s\n", full_path);
            process_directory(full_path); // 递归处理子目录
        } else {
            printf("File: %s\n", full_path);
        }
    }

    closedir(dir);
}

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

    process_directory(argv[1]);

    return 0;
}

这个程序接受一个目录作为参数,然后使用readdir函数读取目录中的条目。对于每个条目,它会检查是否为子目录。如果是子目录,程序会递归地调用process_directory函数来处理子目录。如果不是子目录,程序将输出文件名。

请注意,这个示例没有处理符号链接和其他可能的错误情况。在实际应用中,你可能需要根据你的需求进行相应的调整。

0
看了该问题的人还看了