Filesystem

headkio·2020년 9월 20일
0

C++

목록 보기
33/35
post-thumbnail

Filesystem ?

C++17의 새로운 라이브러리이다. "std::fs"
그 전에는 파일 시스템의 구성요소에 연산할 방법이 없었다.
-> 운영체제에 있는 lib를 사용했다.

기능

경로 합치기

#include <filesystem>

fs::path p1 = "E:\\lecture"
fs::path p2 = "exam"
p1 /= p2; 
  // "E:\\Lecture\\exam"
  // 경로를 합친다.
  
fs::path p1 = "E:\\lecture"
fs::path p2 = "/exam"
p1 /= p2; 
  // "E:\\exam"

fs::path p1 = "E:\\lecture"
fs::path p2 = "exam"
p1 += p2; 
  // "E:\\Lectureexam"
  // 단순 문자열을 합친다.

파일/디렉터리 복사

fs::path orgFile = "c:\\examples\\test1.txt";
fs::path dstFile = "c:\\examples\\test2.txt";

fs::path orgDir = "c:\\examples1";
fs::path dstDir = "c:\\examples2";

fs::copy(orgFile, dstFile); // 파일 복사
fs::copy(orgDir, dstDir); // 디렉터리 복사
fs::copy(orgDir, dstDir, fs::copy_options::recursive); // 디렉터리 복사 (하위폴더 포함)

이름변경+이동

fs::path orgFile = "c:\\examples\\test1.txt";
fs::path dstFile = "c:\\examples\\test2.txt";

fs::rename(orgFile, dstFile);

위치가 같으면 변경과 같다.

삭제

fs::path currentPath = fs::current_path();
fs::create_directories(currentPath / "childDir"); // 폴더 생성 예
fs:: remove(currentPath / "data"); // 삭제 (파일 or 빈폴더)
fs:: remove_all(currentPath / "data"); // 삭제 (폴더안 모든 것)

파일/디렉터리 목록 얻기

for (auto* path : fs::recursive_directory_iterator("C:\\Lecture")) 
{
  std::cout << path << std::endl;
}

재귀적으로 파일을 순회한다.

파일 권한 설정


void PrintPermission(fs::perms permission) 
{
 std::cout << ((permission & fs::perms::owner_read) != fs::perms::none ? "r" : "-")
 << ((permission & fs::perms::owner_write) != fs::perms::none ? "w" : "-")
 << ((permission & fs::perms::owner_exec) != fs::perms::none ? "x" : "-")
 << ((permission & fs::perms::group_read) != fs::perms::none ? "r" : "-")
 << ((permission & fs::perms::group_write) != fs::perms::none ? "w" : "-")
 << ((permission & fs::perms::group_exec) != fs::perms::none ? "x" : "-")
 << ((permission & fs::perms::others_read) != fs::perms::none ? "r" : "-")
 << ((permission & fs::perms::others_write) != fs::perms::none ? "w" : "-")
 << ((permission & fs::perms::others_exec) != fs::perms::none ? "x" : "-")
 << std::endl;
}

int main()
{
  fs::path filePath = "C:\\example\\test.txt";
  PrintPermission(fs::status(filepath).permissions()); 
    // 출력 예시 : --xr--r--
}
profile
돌아서서 잊지말고, 잘 적어 놓자

0개의 댓글