w3resource

List all files and sub-directories in a directory


How to list all files, sub-directories in a directory using C?

Example: Using directory and sub-directories in C

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

static void test(const char *path) {
    struct dirent *dif;
    DIR *dir = opendir(path);
    if (dir == NULL) {
        return;
    }

    while ((dif = readdir(dir)) != NULL) {
        printf("%s\n",dif->d_name);
    }

    closedir(dir);
}

int main(int argc, char** argv) { 
    test("/");
    return 0;
}  

Output:

.
..
workspace
.dockerenv
dev
etc
var
usr
tmp
run
opt
root
fuse.deb
home
sys
srv
proc
mnt
media
sbin
libx32
lib64
lib32
lib
boot
bin

Go to:




Follow us on Facebook and Twitter for latest update.