std::filesystem 예제

C++17 표준에는 파일 시스템 작업을 위한 std::filesystem 라이브러리가 도입되었습니다. 이 라이브러리를 사용하면 파일 및 디렉토리를 쉽게 다룰 수 있으며, 파일 시스템 작업을 보다 편리하게 처리할 수 있습니다.

아래 예제는 std::filesystem를 사용하여 파일 및 디렉토리를 조작하는 간단한 코드입니다:

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

int main() {
    // 현재 작업 디렉토리 출력
    std::cout << "Current Path: " << fs::current_path() << std::endl;

    // 디렉토리 생성
    fs::create_directory("new_directory");

    // 존재하는 디렉토리인지 확인
    bool exists = fs::exists("new_directory");
    std::cout << "Directory exists: " << exists << std::endl;

    // 파일 생성
    std::ofstream file("new_directory/new_file.txt");
    file << "Hello, World!";
    file.close();

    // 디렉토리 내의 파일 목록 출력
    std::cout << "Files in directory:" << std::endl;
    for(const auto& entry : fs::directory_iterator("new_directory")) {
        std::cout << entry.path() << std::endl;
    }

    // 파일 삭제
    fs::remove("new_directory/new_file.txt");

    // 디렉토리 삭제
    fs::remove_all("new_directory");

    return 0;
}

위 코드는 다음과 같은 작업을 수행합니다:

  1. 현재 작업 디렉토리를 출력합니다.
  2. “new_directory”라는 새 디렉토리를 생성합니다.
  3. “new_directory” 디렉토리가 존재하는지 확인합니다.
  4. “new_directory” 내에 “new_file.txt”라는 파일을 생성하고 “Hello, World!”라는 내용을 저장합니다.
  5. “new_directory” 내의 파일 목록을 출력합니다.
  6. “new_directory/new_file.txt” 파일을 삭제합니다.
  7. “new_directory” 디렉토리를 삭제합니다.

std::filesystem는 파일 및 디렉토리 조작에 유용한 많은 함수와 기능을 제공합니다. 위의 예제는 단지 이러한 일부 기능을 보여줄 뿐입니다. 자세한 내용은 C++ 공식 문서를 참조하시기 바랍니다.

#cpp #파일시스템