如何递归地列出目录中C对LINUX [英] How to recursively list directories in C on LINUX
问题描述
我知道有类似这样的问题,但他们中的很多是非常开放的,不帮我太多...
I know that there are questions similar to this, but a lot of them are very open and don't help me too much...
我需要递归列出C编程的所有目录和文件。我已经看着FTW但不包括在我使用(Fedora和Minix的)2个操作系统。我开始从一切,我已经阅读了过去几个小时不同的事情变得很头痛。
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.
如果某人一个code段,我可以看看那将是惊人知道如果任何人都可以给我很好的方向上这一点,我将非常感激。
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>
void listdir(const char *name, int level)
{
DIR *dir;
struct dirent *entry;
if (!(dir = opendir(name)))
return;
if (!(entry = readdir(dir)))
return;
do {
if (entry->d_type == DT_DIR) {
char path[1024];
int len = snprintf(path, sizeof(path)-1, "%s/%s", name, entry->d_name);
path[len] = 0;
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
printf("%*s[%s]\n", level*2, "", entry->d_name);
listdir(path, level + 1);
}
else
printf("%*s- %s\n", level*2, "", entry->d_name);
} while (entry = readdir(dir));
closedir(dir);
}
int main(void)
{
listdir(".", 0);
return 0;
}
这篇关于如何递归地列出目录中C对LINUX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!