How do I traverse into directories?
If I have a folder that has, say, 5 sub-folders, and I want to search for certain files inside each sub-folder(my program is present inside the main folder). How do I make my program traverse into and out of those folders in C++?
I need my program to run on Windows plat开发者_JAVA百科forms.
Thanks!
The most obvious route is to use FindFirstFile
and FindnextFile
, along with SetCurrentDirectory
. One obvious way to traverse the subdirectories is to make your directory traversal routine recursive.
Just use boost's recursive_directory_iterator, and filter the files/directory you want.
boost::filesystem::recursive_directory_iterator iter("your\path");
boost::filesystem::recursive_directory_iterator end;
for (; iter != end; ++iter) {
// check for things like is_directory(iter->status()), iter->filename() ....
// optionally, you can call iter->no_push() if you don't want to
// enter a directory
// see all the possibilities by reading the docs.
}
Just use a stack and implement Depth-First-Search (see wiki) http://en.wikipedia.org/wiki/Depth-first_search
This way you can (with a small as possible stack) traverse any tree like structure (and Windows' file system is tree-like).
精彩评论