Listing all files in a directory is a very common programming requirement. Here we’ll see how to read and display all file names in a directory using C directory entry (dirent) library.
#include <dirent.h>
#include <stdio.h>
int main(void) {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (dir == NULL) {
printf("Failed to open directory.\n");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
if(entry->d_type != DT_DIR) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
This program first opens the current directory (“.”) using opendir() function. In a loop, each entry in the directory is read using readdir() function and printed if its type is not directory.
$ ls
file1.txt file2.txt file3.txt subdir1 subdir2
The current directory above contains 3 text files and two subdirectories. If we run our program in this directory, we’ll see the following output.
$ ./test
file1.txt
file2.txt
file3.txt
This output does not contain the files of the subdirectories.
Read also: List all files including subdirectories.