Search code examples
crecursionprintingfiletree

How to print the file tree of only the found files in a recursive function?


I have a recursive function that searches a path for a given file name. What I am trying to do is to print the files that match, along with their parent directories.

So for a file tree like this:

mydir
   mysubdir
       mysubsubdir
           file1
           file2
   file1
   mysubdir2
       file2

I want to print this when I search for file1:

mydir
    mysubdir
        mysubdir
            file1
    file1

I am able to see each found files' paths, so I thought of constructing a new tree from those paths and then printing that tree, but It seems to me that there must be a much simpler way.


Solution

  • Your function needs the path from the root to the current directory that you are processing. For example, via a const char ** argument, and append to each time you descent a directory (linked list if you don't like recalloc or ensure sufficiently large size up front). When there is match you can print the path starting from the root (see below though).

    To get the short-cut behavior of mydir/file1, you need the path the previous match. This could be another const char ** argument. The print rule is now refined to indent as many levels as previous and current match have common path elements, then print the remaining unique path from current match. This implies a depth first search and sub-directories are visited in sorted order.

    Instead of printing as you go along, you can also record each match in const char *** or as tree as suggested by @wildplasser. Then loop/walk through the result using the same refined print algorithm (if you use a tree you only need to know the level not the prefix path). If you don't do a depth first search, you can sort the array, in this approach. And if you use a tree to store the result, you walked the depth first.