티스토리 뷰

c++

C++ filesystem 사용

삼전동해커 2022. 3. 15. 16:22

일반적으로 파일 데이터의 입출력을 다루는 fstream과는 다른, 파일에 관한 정보(파일 메타데이터)를 다루는 filesystem을 공부해본다. 결국 디렉토리 내에서 원하는 파일을 이름으로 찾아 파일의 데이터를 탐색하고 싶은 경우엔 filesystem과 fstream을 모두 사용해야 한다.

 

#include<iostream>
#include<filesystem>

int main() {
	std::filesystem::path p("./some_file");

	std::cout << "Does " << p << " exist? [" << std::boolalpha << std::filesystem::exists(p) << "]" << std::endl;
	std::cout << "Is " << p << " File? [" << std::boolalpha << std::filesystem::is_regular_file(p) << "]" << std::endl;
	std::cout << "Is " << p << " directory? [" << std::boolalpha << std::filesystem::is_directory(p) << "]" << std::endl;
}

 

위와 같은 코드를 이용해 현재 vs의 경로에서 some_file이라는 이름의 디렉토리가 있는지를 검색해본다.

다음과 같이 some_file이라는 디렉토리가 존재하고, 실행 결과 some_file이 존재하며 file은 아니고 directory라는 결과가 출력된다.

 

 

 

namespace std를 쓰듯이 filesystem도 다음을 추가해 namespace를 사용할 수 있다.

 

namespace fs = std::filesystem;

 

이제 현재경로, 상대 경로, 절대 경로 등을 다루는 api를 살펴보자.

 

다음과 같은 api를 사용해 경로들을 확인할 수 있다.

#include<iostream>
#include<filesystem>

namespace fs = std::filesystem;

int main() {
	fs::path p("./some_file");

	std::cout << "내 현재 경로 : " << fs::current_path() << std::endl;
	std::cout << "상대 경로 : " << p.relative_path() << std::endl;
	std::cout << "절대 경로 : " << fs::absolute(p) << std::endl;
	std::cout << "공식적인 절대 경로 : " << fs::canonical(p) << std::endl;
}

 

 

absoulte와 canonical의 차이점은 absolute는 주어진 경로를 절대 경로로 바꿔주기는 하지만 .이나 ..같은 불필요한 요소들을 포함할 수 있다. canonical은 이러한 요소 없이 모든 경로만을 보여준다.

 

가장 먼저 파일이 존재하지 않는 경우가 있을 수 있으니 exist와 throw를 사용해 파일의 존재여부를 확인해야 한다.

 

디렉토리 안의 모든 파일을 순회하는 방법이 필요했다.

directory_iterator라는 반복자를 사용하면 된다.

 

#include<iostream>
#include<filesystem>
#include<stdio.h>
namespace fs = std::filesystem;

int main() {
		fs::path p("C:\\Users\\crypto\\Desktop\\RaaS\\randsomeware_sample\\test");
		fs::directory_iterator itr(fs::absolute(p));

		while (itr != fs::end(itr)) {
			const fs::directory_entry& entry = *itr;
			std::cout << entry.path() << std::endl;
			itr++;
		}
}

 

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

윈도우 MMF를 이용한 공유 메모리 사용  (0) 2022.05.06
c++ 공유 메모리 사용  (0) 2022.05.04
STL vector 컨테이너  (0) 2021.02.21
C++ this,string 객체,string 배열  (0) 2020.07.06
C++ 객체포인터,객체 배열, 동적 할당  (0) 2020.07.03
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함