[c++] 파일 시스템 접근 권한 검사

C++를 사용하여 파일 시스템에 접근할 때, 시스템 파일 및 디렉토리에 대한 권한을 검사하는 방법에 대해 알아봅시다.

파일 존재 여부 확인

특정 파일이나 디렉토리가 존재하는지 확인할 때, std::filesystem 라이브러리를 사용할 수 있습니다. 아래의 예제는 파일이 존재하는지 확인하는 방법을 보여줍니다.

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    fs::path filePath = "example.txt";
    
    if (fs::exists(filePath)) {
        std::cout << "파일이 존재합니다." << std::endl;
    } else {
        std::cout << "파일이 존재하지 않습니다." << std::endl;
    }
    
    return 0;
}

파일 및 디렉토리 권한 확인

파일 또는 디렉토리의 읽기, 쓰기 및 실행 권한을 확인하려면 std::filesystem::perms 열거형 및 std::filesystem::status 함수를 사용할 수 있습니다.

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    fs::path filePath = "example.txt";
    
    fs::file_status status = fs::status(filePath);
    
    if ((status.permissions() & fs::perms::owner_write) != fs::perms::none) {
        std::cout << "파일에 대한 쓰기 권한이 있습니다." << std::endl;
    } else {
        std::cout << "파일에 대한 쓰기 권한이 없습니다." << std::endl;
    }
    
    return 0;
}

요약

C++에서 파일 시스템에 접근할 때, std::filesystem 라이브러리를 사용하여 파일 또는 디렉토리의 존재 여부를 확인하고, 권한을 검사할 수 있습니다. 이를 통해 안전하고 안정적인 파일 시스템 조작이 가능합니다.

더 자세한 정보는 cppreference.com을 참고하세요.