Use the glibc
scandir function from
<dirent.h> to list all the files in a directory using the C programming language. The
scandir function allows for sorting, comparing and filtering the names of files in the directory. There are default options to list alphabetically through the
alphasort() glibc standard function.
C code to List files in Directory
Below is a simple example, mainly taken from
man scandir, with the execption of adding filtering logic. The filtering logic would typically be done on the name of the file which is found in the
dirent.d_name structure member. If you don’t want a filter instead of passing in the function you can simply set the argument to
Notes on the example
There are a couple of details to note. Firstly, we
#define _DEFAULT_SOURCE. This will allow us to “enable features from the 2008 edition of POSIX, as well as certain BSD and SVID features without a separate feature test macro to control them”. It’s worth reading more on this macro definition as it could have some implications.
Secondly, another function is defined called
scandirat(). This function accepts one more argument which is a file descriptor of a directory to scan a directory from. Again, consult
man scandir for more information.
Running the Example
If you want to try this example download cdirlist-1.0.tar.gz and run the following: