How To List Files in a Directory
There may come atime when you want to work with files/directories in your C programs,
or maybe you're writing a program that needs to list the files in a specific directory.
To work with directories in C we need to include the dirent.h
header file to our code.
First include these library header files
#include <dirent.h>
Then we declare a dirent structure, the dirent structure
holds information about a file or folder in a directory.
struct dirent *dir;
// Open the current working directory
DIR *dir2 = opendir(".");
Now the dir2 variable points to the list of all files
in a directory.
The opendir() takes a path of a direcotry you wish to work
with as an argument, so in this example we're refering to the our current working direcotry,
note that this depends on where you run the program.
Next we'll use a for loop to loop through all those files.
// the readdir returns a dirent strcuture for a specific file/directory
for (dir = readdir(dir2); dir != NULL; dir = readdir(dir2)) {
printf("%s\n", dir->d_name);
}
//close the directory
closedir(dir2);
} else {
printf("Error");
}
In the above code, we first make sured that the direcotry exists otherwise
it prints out an error.
The readdir() returns a dirent structure which points to
a specific file/folder.
We're not doing much here, we;re just printing out
the name of the file/folder in the direcotry.
After you're done working with the directory make sure you always close it
with the closedir() function.
Full Source Code:
#include <dirent.h>
int main() {
// structure that holds info of a file in a dir
struct dirent *dir;
// Open the current working directory
DIR *dir2 = opendir(".");
if (dir2 != NULL) {
// the readdir returns a dirent strcuture for a specific file/folder
for (dir = readdir(dir2); dir != NULL; dir = readdir(dir2)) {
printf("%s\n", dir->d_name);
}
//close the directory
closedir(dir2);
} else {
printf("Error");
}
return 0;
}