2010-06-07 4 views

답변

6

Boost.Filesystem은 훌륭한 라이브러리입니다.

#include <iostream> 
#include <string> 
#include <vector> 
#include <boost/filesystem.hpp> 

using namespace std; 
using namespace boost::filesystem; 

void find_file(const path& root, const string& file_name, vector<path>& found_files) 
{ 
     directory_iterator current_file(root), end_file; 
     bool found_file_in_dir = false; 
     for(; current_file != end_file; ++current_file) 
     { 
       if(is_directory(current_file->status())) 
         find_file(*current_file, file_name, found_files); 
       if(!found_file_in_dir && current_file->leaf() == file_name) 
       { 
         // Now we have found a file with the specified name, 
         // which means that there are no more files with the same 
         // name in the __same__ directory. What we have to do next, 
         // is to look for sub directories only, without checking other files. 
         found_files.push_back(*current_file); 
         found_file_in_dir = true; 
       } 
     } 
} 

int main() 
{ 
     string file_name; 
     string root_path; 
     vector<path> found_files; 

     std::cout << root_path; 
     cout << "Please enter the name of the file to be found(with extension): "; 
     cin >> file_name; 
     cout << "Please enter the starting path of the search: "; 
     cin >> root_path; 
     cout << endl; 

     find_file(root_path, file_name, found_files); 
     for(std::size_t i = 0; i < found_files.size(); ++i) 
       cout << found_files[i] << endl; 
} 
+2

이제는 recursive_directory_iterator가 있으므로 더 간단하게 만들 수 있습니다! – Cubbi

+0

@Cubbi 감사합니다! 나는 최근에 파일 시스템에 추가 된 것을 보지 못했지만 확실히 코드 대신 라이브러리 기능을 사용하는 것이 더 낫다. :) – AraK

1

ACE 크로스 플랫폼 래퍼 많이 있습니다 여기에 전에, 당신은 쉽게 검색 기준을 변경할 수 있습니다 라이브러리를 알면 (당신은 크기와 확장을 조회 할 수 있습니다) 동안 내가 쓴 코드입니다. 특정 경우에는 ACE_Dirent 또는 ACE_OS::scandir/ACE_OS::opendir/ACE_OS::readdir 및 친구 기능을 참조하십시오. ACE는 운영 체제간에 매우 강력한 추상화 계층입니다. 그런 것들이 필요하다면 이것은 갈 길입니다.

관련 문제