如何在 Linux 上用 C 递归列出目录? [英] How to recursively list directories in C on Linux?

查看:32
本文介绍了如何在 Linux 上用 C 递归列出目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要递归地列出 C 编程中的所有目录和文件.我已经研究过 FTW,但它不包含在我使用的 2 个操作系统(Fedora 和 Minix)中.在过去的几个小时里,我读到的所有不同的东西都让我头疼.

I need to recursively list all directories and files in C programming. I have looked into FTW but that is not included with the 2 operating systems that I am using (Fedora and Minix). I am starting to get a big headache from all the different things that I have read over the past few hours.

如果有人知道我可以查看的代码片段,那就太棒了,或者如果有人能给我很好的指导,我将不胜感激.

If somebody knows of a code snippet I could look at that would be amazing, or if anyone can give me good direction on this I would be very grateful.

推荐答案

这是一个递归版本:

#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

void listdir(const char *name, int indent)
{
    DIR *dir;
    struct dirent *entry;

    if (!(dir = opendir(name)))
        return;

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            char path[1024];
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                continue;
            snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
            printf("%*s[%s]
", indent, "", entry->d_name);
            listdir(path, indent + 2);
        } else {
            printf("%*s- %s
", indent, "", entry->d_name);
        }
    }
    closedir(dir);
}

int main(void) {
    listdir(".", 0);
    return 0;
}

这篇关于如何在 Linux 上用 C 递归列出目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆