Search code examples
c++for-looprecursiondirectory-structure

traversing a directory using loops


I know this question has sort of been asked before, but I have a specific example that I was thinking of. Currently I have a piece of code, sorta of pseudocode though, cause I'm not at my work terminal :

void setTree(string dir) {
    add dir to dirlist
    create dir object //contains list of subdirs and files
    for subdir in dir.subs do
        setTree(subdir)
    end
}

Is this possible to do with just for loops, because you can't know at compile time how many sub directories there will be at compile time. Pseudocode is fine or some explanation or algorithm. I don't really need anything because I like my recursive solution best, but I would really like to know if it is possible. As well as the theory behind it.


Solution

  • For the theory see the top-voted answer here: Can every recursion be converted into iteration?

    Practically:

    void setTree(string dir) {
       add dir to dirlist
       while (dirlist not empty) {
       d = dirlist.pop()
       create d object
       for subdir in d.subs do
          append subdir to dirlist
       end
       }
    }
    

    I've tried to follow strange syntax mix-up of your pseudcode, hope it's still readable.