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

C++ std::filesystem::path 함수원형 및 사용법 설명

by 워킹독 2023. 8. 3.
728x90
  • std::filesystem::path는 파일 시스템의 경로를 나타내는 클래스
  • 파일이나 디렉토리의 경로를 표현하고 조작하는 데 사용
  • <filesystem> 헤더에서 제공되며, C++17 이상에서 사용할 수 있음

 

함수 원형

namespace std::filesystem {
    class path;
}
cs


사용법

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

1. 기본 생성자

  • 빈 경로 객체를 생성
std::filesystem::path p;
cs


2. 문자열 생성자

  • 문자열로부터 경로 객체를 생성
std::string filePath = "C:/example/file.txt";
std::filesystem::path p(filePath);
cs

 

3. 복사 생성자

  • 다른 경로 객체로부터 경로 객체를 생성
std::filesystem::path p1("C:/example/file.txt");
std::filesystem::path p2 = p1;
cs

 

4. 연결 연산자

  • 경로를 연결
std::filesystem::path dirPath = "C:/example";
std::filesystem::path filePath = dirPath / "file.txt";
cs

 

5. string() 멤버 함수

  • 경로를 문자열로 변환
std::filesystem::path filePath = "C:/example/file.txt";
std::string strPath = filePath.string();
cs

 

6. filename() 멤버 함수

  • 파일 이름 부분을 얻습니다.
std::filesystem::path filePath = "C:/example/file.txt";
std::string fileName = filePath.filename().string(); // "file.txt"
cs

 

7. parent_path() 멤버 함수

  • 상위 디렉토리 경로를 얻음
std::filesystem::path filePath = "C:/example/file.txt";
std::filesystem::path parentDir = filePath.parent_path(); // "C:/example"
cs

 

8. extension() 멤버 함수

  • 파일의 확장자를 얻음
std::filesystem::path filePath = "C:/example/file.txt";
std::string extension = filePath.extension().string(); // ".txt"
cs

 

9. replace_extension() 멤버 함수

  • 파일의 확장자를 변경합니다.
std::filesystem::path filePath = "C:/example/file.txt";
filePath.replace_extension(".doc");
cs

 

10. exists() 멤버 함수

  • 파일이나 디렉토리가 존재하는지 확인합니다.
std::filesystem::path filePath = "C:/example/file.txt";
bool fileExists = std::filesystem::exists(filePath);
cs

 

 

예시

#include <iostream>
#include <filesystem>
 
namespace fs = std::filesystem;
 
int main() {
    std::string filePathString = "C:/example/file.txt";
    fs::path filePath(filePathString);
 
    std::cout << "File path: " << filePath << std::endl;
    std::cout << "File name: " << filePath.filename() << std::endl;
    std::cout << "Parent directory: " << filePath.parent_path() << std::endl;
    std::cout << "File extension: " << filePath.extension() << std::endl;
 
    filePath.replace_extension(".doc");
    std::cout << "Updated file path: " << filePath << std::endl;
 
    bool fileExists = fs::exists(filePath);
    std::cout << "File exists: " << (fileExists ? "true" : "false"<< std::endl;
 
    return 0;
}
cs


위 예시 코드에서는 std::filesystem::path 클래스를 사용하여 파일 경로를 표현하고 다양한 멤버 함수를 사용하여 경로를 조작하고 정보를 얻는 방법을 보여줍니다.

728x90
반응형

댓글