You could take a look at Glib, there are some file utilities that can be helpful here.
More specifically, you can use g_dir_open function on every file in a directory. If this function sets the GError**error
pointer non-null, then you have tried to open a file, otherwise you’ve just parsed into a subdir…
Your code should look like this:
void parse(const gchar *path)
{
GError *error;
GDir *dir = g_dir_open(path, 0, error);
if(error)
{
// this is a file, not a dir, or a dir which could not be opened...
// you can put all the processing for your file here.
}
else
{
gchar *elem;
while(( elem=g_dir_read_name(dir) ))
{
parse(elem);
free(elem);
}
g_dir_close(dir);
}
}
Say that you have a folder of 10 files, then the parse function will call itself 10 times, once for each file. (Just try it in a debugger!)
0th parse call: opens the directory, then reaches the while loop and calls parse the 1st time for the first file
1st parse call: cannot open the file as directory, so the function ends in the first part of the if block.
back to the 0th parse call: iterates the while loop, calls parse the 2nd time for the next file
2nd parse call: cannot open the file as directory, so the function ends in the first part of the if block.
back to the 0th parse call: iterates the while loop, calls parse the 3rd time for the next file
…
back to the 0th parse call: no more files in the dir, the loop ends.
This is called recursion.
4
solved Recursive scan of folder tree C [closed]