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
Write a C program to print all files and folders.
In C programming, we can list all files and folders in a directory using directory handling functions. This requires the dirent.h header which provides structures and functions to work with directory entries.
Syntax
DIR *opendir(const char *dirname); struct dirent *readdir(DIR *dirp); int closedir(DIR *dirp);
Key Functions
- opendir() − Opens a directory stream for reading
- readdir() − Reads directory entries one by one
- closedir() − Closes the directory stream
Note: This program uses
dirent.hwhich is POSIX standard. On Windows with certain compilers, you might need additional setup or use platform-specific alternatives.
Example
Following is the C program for printing all files and folders in the current directory −
#include <stdio.h>
#include <dirent.h>
int main() {
struct dirent *d;
DIR *dr;
dr = opendir(".");
if(dr != NULL) {
printf("List of Files & Folders:
");
printf("-------------------------
");
while((d = readdir(dr)) != NULL) {
printf("%s
", d->d_name);
}
closedir(dr);
}
else {
printf("Error: Could not open directory!
");
}
return 0;
}
How It Works
- opendir(".") opens the current directory ("." represents current directory)
- readdir() reads each directory entry sequentially until it returns NULL
- d->d_name contains the name of each file or folder
- closedir() releases the directory stream resources
Sample Output
List of Files & Folders: ------------------------- . .. program.c data.txt folder1 image.jpg script.py
Key Points
- The entries "." and ".." represent current and parent directories respectively
- Always check if
opendir()returns NULL to handle errors - Remember to call
closedir()to free system resources - The order of files listed depends on the filesystem implementation
Conclusion
Using dirent.h functions, we can easily traverse directory contents in C. This approach provides a portable way to list files and folders across different Unix-like systems.
Advertisements
