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


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming-exercises/c-snippets/how-to-list-of-files-sub-directories-in-a-directory-using-c.php