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
반응형
'프로그래밍 > C++' 카테고리의 다른 글
| C++ std::filesystem::path 함수원형 및 사용법 설명 (0) | 2023.08.03 |
|---|---|
| STL) inserter, back_inserter, front_inserter 반복자 어댑터(Iterator Adaptor) (0) | 2022.12.14 |
| [C++] 소수(Prime Number) 효율적으로 구하기 (0) | 2022.12.09 |
| [C++] pow, sqrt 함수 정리(제곱, 제곱근, 루트) (0) | 2022.12.09 |
| [C++] 유클리드 호제법 (최대공약수, 최소공배수) (0) | 2022.12.09 |
댓글