본문 바로가기
프로그래밍/C++

C++ std::filesystem::exists() 함수원형 및 사용법 설명

by 워킹독 2023. 8. 9.
728x90
  • std::filesystem::exists() 함수는 지정한 경로의 파일이나 디렉토리가 존재하는지를 확인하는 함수
  • <filesystem> 헤더에서 제공되며, C++17 이상에서 사용할 수 있음

 

함수 원형

namespace std::filesystem {
    bool exists(const path& p);
    bool exists(const path& p, error_code& ec) noexcept;
}
cs


사용법

 std::filesystem::exists() 클래스를 사용하여 파일 경로를 다루는 방법은 다음과 같음

1. 기본 생성자

#include <iostream>
#include <filesystem>
 
namespace fs = std::filesystem;
 
int main() {
    std::string filePathString = "C:/example/file.txt";
    fs::path filePath(filePathString);
 
    if (fs::exists(filePath)) {
        std::cout << "File or directory exists." << std::endl;
    } else {
        std::cout << "File or directory does not exist." << std::endl;
    }
 
    return 0;
}
cs


2. error_code를 사용하여 에러 처리

#include <iostream>
#include <filesystem>
 
namespace fs = std::filesystem;
 
int main() {
    std::string filePathString = "C:/example/file.txt";
    fs::path filePath(filePathString);
 
    std::error_code ec; // 에러 코드 객체
 
    if (fs::exists(filePath, ec)) {
        std::cout << "File or directory exists." << std::endl;
    } else {
        if (ec) {
            std::cout << "Error occurred: " << ec.message() << std::endl;
        } else {
            std::cout << "File or directory does not exist." << std::endl;
        }
    }
 
    return 0;
}
cs

 

std::filesystem::exists() 함수는 지정한 경로의 파일이나 디렉토리가 실제로 존재하는지 여부를 확인하는데 사용됩니다.

파일이나 디렉토리가 존재하는 경우에는 true를 반환하고, 그렇지 않은 경우에는 false를 반환합니다.

error_code를 사용하면 에러 발생 여부를 확인하고 적절한 에러 처리를 수행할 수 있습니다.

728x90
반응형

댓글