Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program to list all files and sub-directories in a directory
In C, we can list all files and sub-directories in a directory using the dirent.h header which provides directory handling functions. This is useful for file system operations and directory traversal programs.
A directory is a container that stores files and other directories in a hierarchical structure. A subdirectory is a directory contained within another directory, creating nested folder structures.
Note: This program requires a POSIX-compliant system (Linux/Unix/macOS). On Windows, you may need to use different headers or compile with specific flags.
Syntax
DIR *opendir(const char *dirname); struct dirent *readdir(DIR *dirp); int closedir(DIR *dirp);
Example: List Files in Current Directory
The following program demonstrates how to list all files and subdirectories in the current directory −
#include <stdio.h>
#include <dirent.h>
int main() {
struct dirent *entry;
DIR *dir = opendir(".");
if (dir == NULL) {
printf("Error: Cannot open directory!<br>");
return 1;
}
printf("Files and directories in current folder:<br>");
printf("----------------------------------------<br>");
while ((entry = readdir(dir)) != NULL) {
printf("%s<br>", entry->d_name);
}
closedir(dir);
return 0;
}
How It Works
-
opendir(".")opens the current directory ("." represents current directory) -
readdir(dir)reads each entry sequentially and returns a pointer todirentstructure -
entry->d_namecontains the name of the file or directory -
closedir(dir)closes the directory stream to free resources
Key Points
- Always check if
opendir()returns NULL to handle errors gracefully - The entries include "." (current directory) and ".." (parent directory)
- Remember to call
closedir()to avoid resource leaks - This function lists both files and subdirectories without distinction
Conclusion
Using dirent.h functions, we can easily traverse directories in C. The opendir(), readdir(), and closedir() functions provide a simple interface for directory listing operations.
Advertisements
