Learn How To List Names of all Files, Sub Directories and Contents of Directory in C Programming Language. Get the list of all files and sub directories in a directory using dirent.h header file.
This is a simple directory lister c program that enlists the names of all the files in a directory. We have used opendir() method that passes the directory name to the pointer which is then used by readdir() method to return the names of the files and sub directories in that directory.
About Dirent.h
The dirent.h header file is used to work with the directories in C programming. DIR is a type representing a directory stream. The struct dirent structure is a structure type used to return information about directory entries.
Must Read: How To Create User Defined Header Files in C Programming
C Program To List Contents of Directory using dirent.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include<dirent.h> #include<stdio.h> int main() { char directory_name[10]; DIR *ptr; struct dirent *directory; printf("Enter Directory Name:\t"); scanf("%s", directory_name); ptr = opendir(directory_name); printf("\nDirectory %s\n", directory_name); while((directory = readdir(ptr)) != NULL) { printf("%s\n", directory->d_name); } closedir(ptr); } |
Output

If you have any compilation error or doubts in this C program to list all the sub directories and folders in a given directory, let us know about it in the comment section below. Find more about dirent.h here.
Does this program also lists the hidden files and sub directories?
Yes. This Directory Lister C Program does enlists the Hidden files of my directory.
There are so many functions and header files in C library that I have not even heard of. This is something unique. Thanks. Keep updating us with the same.