2017-10-05 11 views
0

디렉토리의 폴더 목록을 가져와야하지만 폴더 만 가져와야합니다. 파일이 필요하지 않습니다. 폴더 만. 필터를 사용하여 폴더인지 확인하지만 작동하지 않으며 모든 파일과 폴더가 출력됩니다.C++ 폴더 만 검색

string root = "D:\\*"; 
cout << "Scan " << root << endl; 
std::wstring widestr = std::wstring(root.begin(), root.end()); 
const wchar_t* widecstr = widestr.c_str(); 
WIN32_FIND_DATAW wfd; 
HANDLE const hFind = FindFirstFileW(widecstr, &wfd); 

이렇게하면 폴더인지 확인합니다.

if (INVALID_HANDLE_VALUE != hFind) 
    if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) 
     if (!(wfd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) 

문제를 해결하는 방법은 무엇입니까?

+0

https://stackoverflow.com/questions/5043403/listing-only-folders-in-directory –

+1

은 #INCLUDE 과이를 지원하지 현재 DIR – Xom9ik

+1

창에 맹세. * fSearchOp *를 [FindExSearchLimitToDirectories'로 설정하면 [FindFirstFileEx'] (https://msdn.microsoft.com/en-us/library/windows/desktop/aa364419(v=vs.85).aspx)하실 수 있습니다. ] (https://msdn.microsoft.com/en-us/library/windows/desktop/aa364416 (v = vs.85) .aspx) -이 플래그는 현재 적용되지 않습니다 – RbMm

답변

2

이 함수는 폴더를 주어진 벡터로 수집합니다. 하드 방법, 그리고 쉬운 방법 : true로 재귀을 설정하면이 작업을 수행하는 방법은 두 가지가 있습니다 https://stackoverflow.com/a/46511952/8666197

2

에서 수정 등

// TODO: proper error handling. 

void GetFolders(std::vector<std::wstring>& result, const wchar_t* path, bool recursive) 
{ 
    HANDLE hFind; 
    WIN32_FIND_DATA data; 
    std::wstring folder(path); 
    folder += L"\\"; 
    std::wstring mask(folder); 
    mask += L"*.*"; 

    hFind=FindFirstFile(mask.c_str(),&data); 
    if(hFind!=INVALID_HANDLE_VALUE) 
    { 
     do 
     { 
      std::wstring name(folder); 
      name += data.cFileName; 
      if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) 
       // I see you don't want FILE_ATTRIBUTE_REPARSE_POINT 
       && !(data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) 
      { 
       // Skip . and .. pseudo folders. 
       if (wcscmp(data.cFileName, L".") != 0 && wcscmp(data.cFileName, L"..") != 0) 
       { 
        result.push_back(name); 
        if (recursive) 
         // TODO: It would be wise to check for cycles! 
         GetFolders(result, name.c_str(), recursive); 
       } 
      } 
     } while(FindNextFile(hFind,&data)); 
    } 
    FindClose(hFind); 
} 

폴더 안에 폴더 안에 폴더를 검색한다 .

어려운 방법은 FindFirstFileFindNextFile을 기반으로하며 필요에 따라 디렉토리를 필터링합니다. Stack Overflow와 인터넷의 나머지 부분에서이 접근 방식을 설명하는 bazillion 샘플을 찾을 수 있습니다.

쉬운 방법 : 표준 directory_iterator 클래스를 사용하거나 하위 디렉토리로 다시 이동해야하는 경우 recursive_directory_iterator 클래스를 사용하십시오. 당신은 C++ (17)에 도입 된 <filesystem> 헤더 파일을 포함해야합니다

for (const auto& entry : directory_iterator(path(L"abc"))) { 
    if (is_directory(entry.path())) { 
     // Do something with the entry 
     visit(entry.path()); 
    } 
} 

:이 솔루션은 간단 1 같습니다.

참고 : 최신 버전의 Visual Studio 2017 (15.3.5)을 사용하면 아직 namespace std이 아닙니다. 대신 namespace std::experimental::filesystem을 참조해야합니다. ... 가상 디렉토리를 필터링 할 필요가 없음을


1 특히주의; 그것들은 디렉토리 반복자에 의해 반환되지 않는다.