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
How can I get the list of files in a directory using C or C++?
Listing files in a directory is used to write a program that opens a specified folder (e.g: "/myfiles"), reads its contents, and displays the names of each file and subfolder one by one.
In C, to see all the files in a directory, you can use special system functions that let you read the directory's contents.
In real life, we open folder to see the contents inside the files. Similarly, in C, we can write a program to display all the files and folders in a directory.
Syntax
DIR *opendir(const char *dirname); struct dirent *readdir(DIR *dirp); int closedir(DIR *dirp);
Algorithm
Following is the algorithm to get the list of files in a directory using C −
Begin
Declare a pointer dr to the DIR type.
Declare another pointer en of the dirent structure.
Call opendir() function to open all file in present directory.
Initialize dr pointer as dr = opendir(".").
If(dr)
while ((en = readdir(dr)) != NULL)
print all the file name using en->d_name.
call closedir() function to close the directory.
End.
Example: List Files in Current Directory
This program opens the current folder and prints the names of all files and subfolders inside it −
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dr;
struct dirent *en;
dr = opendir("."); // open current directory
if (dr) {
printf("Files and directories in current folder:\n");
while ((en = readdir(dr)) != NULL) {
printf("%s\n", en->d_name); // print directory/file name
}
closedir(dr); // close directory
} else {
printf("Could not open directory\n");
}
return 0;
}
Files and directories in current folder: . .. main.c notes.txt images data.csv
Example: List Files in Specific Directory
This program lists files in a specified directory path −
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dr;
struct dirent *en;
char path[] = "/tmp"; // specify directory path
dr = opendir(path);
if (dr) {
printf("Files in %s directory:\n", path);
while ((en = readdir(dr)) != NULL) {
// Skip . and .. entries
if (en->d_name[0] != '.') {
printf("%s\n", en->d_name);
}
}
closedir(dr);
} else {
printf("Could not open directory: %s\n", path);
}
return 0;
}
Files in /tmp directory: temp_file.txt cache_data log_file.log
Key Points
- opendir() returns NULL if the directory cannot be opened
- readdir() returns NULL when no more entries are available
- Always call closedir() to free allocated resources
- The entries "." (current dir) and ".." (parent dir) are included in the listing
- Use dirent.h header for directory operations in C
Conclusion
Directory listing in C uses the opendir(), readdir(), and closedir() functions. Always check if opendir() succeeds before reading entries and remember to close the directory when done.
