boost库之filesystem #include <iostream> #include <string> #include <vector> #include <set> #include <iterator> #include <functional> #include <boost/noncopyable.hpp> #include <boost/tokenizer.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <boost/filesystem/exception.hpp> using namespace std; using namespace boost; using namespace boost::algorithm; using namespace boost::filesystem; template<typename InputIterator, typename OutputIterator, typename Predicate> OutputIterator copy_if(InputIterator begin, InputIterator end, OutputIterator destBegin, Predicate p) { while (begin != end) { if (p(*begin))*destBegin++ = *begin; ++begin; } return destBegin; } class FilePath : public noncopyable { public: FilePath(string filepath); //para: file path. ~FilePath(){} public: inline void FindInSubPath(bool flag = false){subpath = flag;} //lie that: *.map3 *.wav ... void SetSuffix(const string &suffixs); void GetFiles(vector<string> &files); private: void Find(boost::filesystem::path &p); private: string filepath; bool subpath; vector<string> file; set<string> suffix; bool usesf; }; FilePath::FilePath(string _filepath): filepath(_filepath), subpath(false), usesf(false) {} void FilePath::SetSuffix(const string &suffixs) { string temp(suffixs); to_lower(temp); tokenizer<> sf(temp); for(tokenizer<>::iterator itr = sf.begin(); itr != sf.end();++itr) { //cout<<*itr<<endl; suffix.insert(*itr); } usesf = true; } void FilePath::GetFiles(vector<string> &files) { boost::filesystem::path _filepath(filepath,boost::filesystem::native); Find(_filepath); files = file; } void FilePath::Find(boost::filesystem::path &p) { try { if(boost::filesystem::exists(p) == true) { boost::filesystem::directory_iterator item_begin(p); boost::filesystem::directory_iterator item_end; for(;item_begin != item_end; item_begin++ ) { if (boost::filesystem::is_directory( * item_begin) == true && subpath == true) { Find(*item_begin); } else { string filename = item_begin->native_file_string(); if(usesf == true) { //string suffix_(filename,filename.rfind(".")+1); //Op op(filename); //copy_if(suffix.begin(),suffix.end(),file.begin(),op); to_lower(filename); set<string>::iterator itr = suffix.begin(); while(itr != suffix.end()) { if(ends_with(filename, *itr)== true) file.push_back(filename); itr ++; } } else { file.push_back(filename); } } } } } catch(boost::filesystem::filesystem_error e) { cout<<e.what()<<endl; } } int main() { FilePath fp("D://c++"); vector<string> vs; fp.FindInSubPath(true); fp.SetSuffix(".bmp .wav .h .cpp .cxx .c .hpp"); fp.GetFiles(vs); copy(vs.begin(),vs.end(),ostream_iterator<string>(cout,"/n")); std::system("pause"); return 1; }