Loop through folders without recursion
I was looking for an algorithm, so OS is not problem, in how to loop through folders without the use of recursion.
Recursion is not the answer because recursion cannot go to "infini开发者_JAVA百科ty" and beyond, while a "while loop" can get there.
Programming language doesn't matter.
You can use a stack data structure for depth-first traversal. Here is some sample code in C#:
var stack = new Stack<string>();
stack.Push(@"C:\");
while (stack.Count > 0)
{
var currentDirectory = stack.Pop();
Console.WriteLine("Visiting: " + currentDirectory);
foreach (var childDirectory in Directory.GetDirectories(currentDirectory))
{
stack.Push(childDirectory);
}
}
精彩评论