본문 바로가기

Study/C++

C++ filesystem:: C++에서 파일디렉토리/파일 시스템 읽어오기

 

C++17에서 추가된 <filesystem>라이브러리를 이용하면 파일 시스템을 읽어올 수 있다.

원래 boost에 있던건데 정식으로 추가됐다.

 

 

사용법:

#include <experimental/filesystem>
namespace std::experimental::filesystem;
g++ main.cpp -lstdc++fs 

gcc 8버전 이상부터는 experimental을 빼고 그냥 #include <filesystem>하면 된다.

 

 

 

 

폴더 내 모든 폴더명/ 파일명을 긁어오는 예제

for(auto& p: fs::recursive_directory_iterator(path))
{
  cout << p << endl;							//결과: root/dir1/text.txt
  cout << p.path().filename() << endl;			//결과: "test.txt"
  cout << p.path().filename().string() << endl;	//결과: test.txt
}

 

 

 

 

 

참고

https://en.cppreference.com/w/cpp/filesystem

 

Filesystem library - cppreference.com

The Filesystem library provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories. The filesystem library was originally developed as boost.filesystem, was published as the technical sp

en.cppreference.com

https://docs.microsoft.com/ko-kr/cpp/standard-library/filesystem?view=vs-2019

 

 

이 문서의 내용 --> 경로, 파일 및 디렉터리에 대한 정보를 조작하고 검색하는 클래스 및 함수에 액세스할 수 있도록 헤더를 포함합니다. Include the header for access to classes and functions that manipulate and retrieve information about paths, files and directories. 구문Syntax #include // C++-standard header file n

docs.microsoft.com

 

[C++ reference :: directory_iterator]

 

std::filesystem::directory_iterator - cppreference.com

class directory_iterator; (since C++17) directory_iterator is a LegacyInputIterator that iterates over the directory_entry elements of a directory (but does not visit the subdirectories). The iteration order is unspecified, except that each directory entry

en.cppreference.com

https://stackoverflow.com/questions/39231363/fatal-error-filesystem-no-such-file-or-directory

 

fatal error: filesystem: No such file or directory

Using, CentOs 7.1, gcc version 6.1.0 (GCC) I receive this error: fatal error: filesystem: No such file or directory on this line #include compiling with g++ main.cpp -o mai...

stackoverflow.com

https://stackoverflow.com/questions/612097/how-can-i-get-the-list-of-files-in-a-directory-using-c-or-c

 

How can I get the list of files in a directory using C or C++?

How can I determine the list of files in a directory from inside my C or C++ code? I'm not allowed to execute the ls command and parse the results from within my program.

stackoverflow.com

https://stackoverflow.com/questions/33149878/experimentalfilesystem-linker-error

 

experimental::filesystem linker error

I try to use the new c++1z features actually on the head of development within gcc 6.0. If I try this little example: #include #include namespace ...

stackoverflow.com