티스토리 뷰
목차
반응형
C++ 폴더 내 파일 이름, 개수 리스트 만들기 (vector 응용 예제)
[Get c++ folder file list using vector]
소개할 예제는 C++에서 제공하는 read_directory() 함수를 이용합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <iostream> #include <string> #include <vector> #include <algorithm> #include <iterator> typedef std::vector<std::string> stringvec; int main() { stringvec v; read_directory(".", v); std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "\n")); } | cs |
추가로 아래 4개 방법으로도 폴더 내 파일 이름, 개수 리스트를 벡터로 구현할 수 있습니다.
- boost::filesystem::directory_iterator
- std::filesystem::directory_iterator (C++17)
- opendir() / readdir() / closedir() (POSIX)
- FindFirstFile() / FindNextFile() / FindClose() (Windows)
[Get c++ folder file list using vector]
C++을 이용해 폴더 내부 파일 List 만드는 방법 4가지
① boost::filesystem
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <boost/filesystem.hpp> struct path_leaf_string { std::string operator()(const boost::filesystem::directory_entry& entry) const { return entry.path().leaf().string(); } }; void read_directory(const std::string& name, stringvec& v) { boost::filesystem::path p(name); boost::filesystem::directory_iterator start(p); boost::filesystem::directory_iterator end; std::transform(start, end, std::back_inserter(v), path_leaf_string()); } | cs |
Boost Filesystem Library Version 3 참조
② std::filesystem (C++17)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <filesystem> struct path_leaf_string { std::string operator()(const std::filesystem::directory_entry& entry) const { return entry.path().leaf().string(); } }; void read_directory(const std::string& name, stringvec& v) { std::filesystem::path p(name); std::filesystem::directory_iterator start(p); std::filesystem::directory_iterator end; std::transform(start, end, std::back_inserter(v), path_leaf_string()); } | cs |
③ opendir() / readdir() / closedir() (POSIX)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <sys/types.h> #include <dirent.h> void read_directory(const std::string& name, stringvec& v) { DIR* dirp = opendir(name.c_str()); struct dirent * dp; while ((dp = readdir(dirp)) != NULL) { v.push_back(dp->d_name); } closedir(dirp); } | cs |
Reference: readdir – The Open Group
④ FindFirstFile() / FindNextFile() / FindClose() (Windows)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <windows.h> void read_directory(const std::string& name, stringvec& v) { std::string pattern(name); pattern.append("\\*"); WIN32_FIND_DATA data; HANDLE hFind; if ((hFind = FindFirstFile(pattern.c_str(), &data)) != INVALID_HANDLE_VALUE) { do { v.push_back(data.cFileName); } while (FindNextFile(hFind, &data) != 0); FindClose(hFind); } } | cs |
C++ 폴더 내 파일 이름, 개수 리스트 만들기 (vector 응용 예제)
반응형