본문 바로가기

C++

[C++] 폴더 내 파일목록 읽기

특정 폴더 내에 존재하는 파일목록을 가져온다.

 _findfirst 함수를 이용하여 핸들을 얻고 _findnext 함수를 이용하여 폴더 내 모든 파일을 검색한다. 결과가 -1이 리턴되면 종료한다.

검색할 위치는  _findfirst 함수에 위치+검색파일형식의 문자열로 전달한다.


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
#include <io.h>
// find all matched file in specified directory
// [INPUT]
//   >> const std::string& _path        Search path        ex) c:/directory/
//   >> const std::string& _filter        Search filter    ex) *.exe or *.*
// [RETURN]
//   >> std::vector<std::string>        All matched file name & extension
std::vector<std::string> get_files_inDirectory(const std::string& _path, const std::string& _filter)
{
    std::string searching = _path + _filter;
 
    std::vector<std::string> return_;
 
    _finddata_t fd;
    long handle = _findfirst(searching.c_str(), &fd);  //현재 폴더 내 모든 파일을 찾는다.
 
    if (handle == -1)    return return_;
    
    int result = 0;
    do 
    {
        return_.push_back(fd.name);
        result = _findnext(handle, &fd);
    } while (result != -1);
 
    _findclose(handle);
 
    return return_;
}
cs


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

[C++] 현재 시간 얻기  (0) 2016.10.24
[C++] file TO vector string  (0) 2016.10.13
[C++] string TO vector string  (0) 2016.10.13