0

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.

1 Answers1

0

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.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • Will only having the path of the previous match be sufficient to avoid printing some directories more than once? – LonelyBishop Mar 30 '21 at 12:04
  • Can you think of a counter example? Meaning you current match has something in common with a path that you printed out before the previous match but not the previous match. I could certainly be wrong. – Allan Wind Mar 30 '21 at 12:09
  • @LonelyBishop You either need two passes, or store the gathered information (in a tree-like structure) and do the printing *after* the treewalk. – wildplasser Mar 30 '21 at 12:14
  • @AllanWind In the second approach you mentioned: How should I record each match int the pointer? If I store the full paths of each, shouldn't I have to create a new tree to print them correctly? Sorry for the follow up questions. – LonelyBishop Mar 30 '21 at 12:23
  • Looping over a list of sorted paths is equivalent to walking a tree depth first while visiting sub-directories in sorted order. The key is having a shared variable that all results are stored in. This done easily by passing down an argument. – Allan Wind Mar 30 '21 at 12:27