iNukeLaPeste iNukeLaPeste - 4 months ago 10x
Linux Question

List files in directories using Glob() in C

Basically, so far I have this code:

#include <glob.h>
#include <string.h>
#include <stdio.h>

# define ERROR 1
# define FAILURE -1

int main(int ac, char **av)
glob_t globlist;
int i;

i = 0;
if (ac == 1)
return (-1);
if (glob(av[1], GLOB_PERIOD, NULL, &globlist) == GLOB_NOSPACE
|| glob(av[1], GLOB_PERIOD, NULL, &globlist) == GLOB_NOMATCH)
return (FAILURE);
if (glob(av[1], GLOB_PERIOD, NULL, &globlist) == GLOB_ABORTED)
return (ERROR);
while (globlist.gl_pathv[i])
printf("%s\n", globlist.gl_pathv[i]);
return (0);

When I type
./a.out "*"
for example it prints all my files where I am, aswell as directories, but it doesn't print what is inside directories. How should I do to print ALL files, including sub-files/folders?



Use nftw() instead of glob() if you want to examine entire trees, rather than one specific path and filename pattern.

(It is absolutely silly to reinvent the wheel by going at it using opendir()/readdir()/closedir(), especially because nftw() should handle filesystem changes gracefully, whereas self-spun tree walking code usually ignores all the hard stuff, and only works in optimal conditions on your own machine, failing in spectacular and wonderful ways elsewhere.)

In the filter function, use fnmatch() to decide whether the file name is acceptable using glob patterns.

If you wish to filter using regular expressions instead, use regcomp() to compile the pattern(s) before calling nftw(), then regexec() in your filter function. (Regular expressions are more powerful than glob patterns, and they are compiled to a tight state machine, so they are quite efficient, too.)

If you are unsure about the difference, the Wikipedia articles on glob patterns and regular expressions are very useful and informative.

All of the above are defined in POSIX.1-2008, so they are portable across all POSIX-y operating systems.