C++17 표준 라이브러리의 파일 시스템 라이브러리 소개

Twitter icon류광, 2017-07-22 13:07
이어지는 핵심 C++ 표준 라이브러리" 부록 공개. 이번에는 C++17에 추가된 파일 시스템 라이브러리를 소개합니다.

"핵심 C++ 표준 라이브러리" 부록 A 중 C++17에 추가된 파일 시스템 라이브러리를 소개하는 글입니다.

파일 시스템 라이브러리

C++14까지 C++ 표준 라이브러리에는 파일 입출력을 위한 수단은 있었지만 파일 시스템을 위한 수단은 없었다. C++17에서 드디어 C++도 파일 시스템 라이브러리를 가지게 되었다. 이 파일 시스템 라이브러리는 원래 boost.filesystem으로 출발해서 TS(Technical Specification) 단계를 거쳐서 표준 라이브러리에까지 들어오게 된 것이다. C++ 파일 시스템 라이브러리의 모든 형식과 함수는 std::filesystem 이름공간에 속하며, 필요한 헤더는 <filesystem>이다.

파일 시스템 라이브러리에는 파일의 경로를 나타내는 path와 디렉터리의 한 항목(보통의 파일뿐만 아니라 하위 디렉터리, 기호 링크, 소켓, 파이프 등도 포함)을 나타내는 directory_entry, 파일의 종류와 상태를 나타내는 file_status, 가용 디스크 용량을 위한 space_info, 파일 시간을 위한 file_time_type 등 다양한 클래스가 있으며, 디렉터리 반복(운행)을 위한 두 반복자 클래스 directory_iteratorrecursive_directory_iterator도 제공한다. 또한, 파일 접근 권한, 파일 종류, 복사 옵션, 디렉터리 반복 운행) 옵션을 위한 열거형들(perms, file_type 등)도 갖추어져 있다.

이러한 형식들 외에, 실질적인 파일 시스템 연산들을 수행하는 다양한 비멤버 함수들이 있다. 예를 들어 directory_entry 클래스에는 디렉터리를 생성하거나 파일을 복사하는 멤버 함수가 없다. 디렉터리 생성은 비멤버 함수 create_directorycreate_directories가, 복사는 비멤버 함수 copycopy_file이 담당한다. 그 밖에 rename, resize_file, current_path, exits 등 경로와 파일, 디렉터리를 다루는 데 필요한 다양한 함수가 있다. 또한, is_directory, is_empty, is_regular_file 등 주어진 디렉터리 항목의 종류를 판정하는 술어 함수들도 있다. 표 A.1은 파일 시스템 라이브러리의 구성요소들을 나열한 것이다.

void h()
{
    namespace fs = std::filesystem;
    fs::create_directory("foo");

    // create_directories는 경로 중간의 디렉터리들까지 생성해준다.
    fs::create_directories("foo/bar/abc/123") 

    // 보통의 파일을 생성하려면 파일 입출력 라이브러리가 필요하다.
    std::ofstream("foo/bar/abc/file.txt");            

    // 반복자를 이용해서 foo 디렉터리와 그 하위 디렉터리의 
    // 모든 항목을 훑는다.
    for(auto&& x: fs::recursive_directory_iterator('foo')) {
        cout << x.path() << endl;
    }
}

표 A.1 파일 시스템 라이브러리의 구성

        형식  
path            recursive_directory_iterator    perms
filesystem_error    file_status         copy_options
directory_entry     space_info          directory_options
directory_iterator  file_type           file_time_type
        함수  
absolute        create_directories      permissions
system_complete     create_hard_link        read_symlink
canonical       create_symlink          remove
weakly_canonical    create_directory_symlink    remove_all
relative        current_path            rename
proximate       exists              resize_file
copy            equivalent          space
copy_file       file_size           status
copy_symlink        hard_link_count         symlink_status
create_directory    last_write_time         temp_directory_path
        파일 종류 및 상태 판정 술어    
is_block_file       status_known            is_regular_file
is_character_file   is_fifo             is_socket
is_directory        is_other            is_symlink
is_empty
태그: C++ C++17 표준 라이브러리

comments powered by Disqus