Charlie Charlie - 1 year ago 64
Linux Question

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...

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.


Answer Source

Here is a recursive version:

#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)))
    if (!(entry = readdir(dir)))

    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)
            printf("%*s[%s]\n", level*2, "", entry->d_name);
            listdir(path, level + 1);
            printf("%*s- %s\n", level*2, "", entry->d_name);
    } while (entry = readdir(dir));

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