C++でdirectory walking
ディレクトリを再帰的に降りていき、コールバック関数を呼び出す。
Boost::filesystemとboost::functionの合わせ技でOK。
#include <iostream>
#include <functional>
#include <algorithm>
#include <boost/function.hpp>
#include <boost/filesystem/operations.hpp>
using namespace boost;
using namespace boost::filesystem;
void dir_walk(const path& top, function<void (const path& )> f) {
directory_iterator end;
for(directory_iterator it(top);it != end;++it) {
path p = *it;
f(p); //call back functionの呼び出し(表示)
if(is_directory (p)) { //dirctoryなら再帰呼び出し
dir_walk(p, f);
}
}
}
void print_dir(const path& p) {
std::cout << p.string() << std::endl;
}
void print_size(const path& p) {
if(!is_directory(p)) {
std::cout << file_size(p) << " ";
}
std::cout << p.string() << std::endl;
}
int main(void)
{
function<void (const path& path)> f;
// f = &print_dir;
f = &print_size;
path dir(".");
dir_walk(dir, f);
return 0;
}
rambdaとかbindとかも挑戦したけど駄目だった。for文は、for_eachにしたいんだけどなぁ。出来る人はできるんだろう。
とりあえず、Perlでも、Pythonでも出来た。ていうか、一冊の本を3つの言語でやっていくのは効率が悪い気がした。
The comments to this entry are closed.


Comments