Skip to content

Instantly share code, notes, and snippets.

@g761007
Created January 16, 2013 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save g761007/4545581 to your computer and use it in GitHub Desktop.
Save g761007/4545581 to your computer and use it in GitHub Desktop.
C++ like python os.walk
#include <vector>
#include <tuple>
#include <boost/filesystem.hpp>
typedef std::tuple<boost::filesystem::path, std::vector<boost::filesystem::path>, std::vector<boost::filesystem::path>> WALK_ITEM;
typedef std::vector<WALK_ITEM> WALK_PATHS;
void display(const WALK_ITEM &item)
{
boost::filesystem::path p(get<0>(item));
std::vector<boost::filesystem::path> dirs(get<1>(item));
std::vector<boost::filesystem::path> files(get<2>(item));
std::cout << "path: " << p << std::endl;
std::cout << "directory: " << std::endl;
for (std::vector<boost::filesystem::path>::const_iterator it(dirs.begin()); it != dirs.end(); ++it)
{
cout << " " << (*it).filename() << std::endl;
}
std::cout << "files: " << std::endl;
for (std::vector<boost::filesystem::path>::const_iterator it(files.begin()); it != files.end(); ++it)
{
cout << " " << (*it).filename() << std::endl;
}
cout << std::endl;
}
bool walk(const boost::filesystem::path &p, WALK_PATHS &data)
{
try {
if (boost::filesystem::is_directory(p)) {
std::vector<boost::filesystem::path> dirs;
std::vector<boost::filesystem::path> files;
typedef std::vector<boost::filesystem::path> vec;
vec v;
copy(boost::filesystem::directory_iterator(p), boost::filesystem::directory_iterator(), std::back_inserter(v));
for (vec::const_iterator it(v.begin()); it != v.end(); ++it)
{
if (boost::filesystem::is_directory(*it)) {
dirs.push_back(*it);
} else if (boost::filesystem::is_regular_file(*it)) {
files.push_back(*it);
}
}
data.push_back(make_tuple(p, dirs, files));
for (vec::const_iterator it(dirs.begin()); it != dirs.end(); ++it)
{
walk(*it, data);
}
return true;
}
} catch (std::exception e) {
std::cout << "error: " << e.what() << std::endl;
}
return false;
}
int main()
{
FS::path p("C:\\");
WALK_PATHS paths;
if (walk(p, paths)) {
for (WALK_PATHS::const_iterator it(paths.begin()); it != paths.end(); ++it) {
display((*it));
}
} else {
cout << "Walk " << p.c_str() << " failure..." << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment