Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

CPP-Shooter's Life

Directory_iterator 본문

Programming/C++

Directory_iterator

CPP-Shooter 2019. 1. 14. 09:37

현재 폴더 내에 존재하는 파일들만 순회(주의 : 서브 폴더는 제외)하면서 찾기 위한 표준 반복자로서,

C++17에 추가되었다.

포함할 소스와 사용할 네임스페이스는 아래와 같다.


#include <filesystem>

using namespace std::experimental; //<filesystem> 내부 API들이 이걸로 감싸져 있다.. (VS2015 기준.)


2017년 10월 기준으로 아직은 정식 표준이 아니다. (실험 기능)



** 예제 코드


bool CAtlasGroup::LoadAtlas_All()

{

   //폴더 내 모든 스프라이트를 찾아 로드하고,

   //SpriteCache를 다시 구성하여 저장시킨다.

   if (sprCache == nullptr)

      sprCache = new SDLSpriteCache();


   sprCache->ClearCache();


   //폴더 내에 json 기반의 txt 파일을 전부 찾는다.

   for (const auto& _fileObj : filesystem::directory_iterator(folderPath))

   {

      if (_fileObj.path().extension() == ".txt")

      {

      //전체 경로에서 순수 파일 이름만 추출

      std::string fileName = _fileObj.path().filename().string();

….

      }

   }


   //재구성한 SpriteCache를 파일로 저장

   sprCache->SaveToFile(groupName.c_str());

   return true;

}


위 코드에서

for (const auto& _fileObj : filesystem::directory_iterator(folderPath))

{

  //Do Something

}


이 부분을 보면 범위 기반 for문을 활용하고 생성 인자로 폴더 경로를 지정하며,

폴더 내 파일이 있을 때 반복한다.

더 이상 찾을 파일이 없으면 루프를 빠져나온다.


여기서 _fileObj 의 정확한 타입은 directory_entry 이며

이 안에 path 라는 파일 경로 처리에 특화된 표준 클래스 타입의 객체를 가지고 있다.


자매품(?)으로 recursive_directory_iterator 가 있다.


이거는 기준 폴더의 파일 뿐만이 아니라 서브 폴더까지 재귀적으로 타고 들어간다.

'Programming > C++' 카테고리의 다른 글

정규표현식으로 특정 확장자의 파일을 모두 찾기  (0) 2019.01.14