Namespaces
Variants

std::filesystem::directory_entry:: file_size

From cppreference.net
std:: uintmax_t file_size ( ) const ;
(1) (C++17 이후)
std:: uintmax_t file_size ( std:: error_code & ec ) const noexcept ;
(2) (C++17 이후)

파일 크기가 이 directory_entry 에 캐시되어 있으면 캐시된 값을 반환합니다. 그렇지 않으면 다음을 반환합니다:

2) std:: filesystem :: file_size ( path ( ) , ec ) .

목차

매개변수

ec - 비예외 발생 오버로드에서 오류 보고를 위한 출력 매개변수

반환값

참조된 파일 시스템 객체의 크기입니다.

예외

noexcept 로 표시되지 않은 모든 오버로드는 메모리 할당이 실패할 경우 std::bad_alloc 을(를) throw할 수 있습니다.

1) 기본 OS API 오류 발생 시 std::filesystem::filesystem_error 를 발생시킵니다. 이는 p 를 첫 번째 경로 인수로, OS 오류 코드를 오류 코드 인수로 구성되어 생성됩니다.
2) OS API 호출이 실패할 경우 std:: error_code & 매개변수를 OS API 오류 코드로 설정하고, 오류가 발생하지 않을 경우 ec. clear ( ) 를 실행합니다.

예제

주어진 디렉토리에 있는 파일 목록을 사람이 읽기 쉬운 형태의 크기와 함께 출력합니다.

#include <cmath>
#include <cstdint>
#include <filesystem>
#include <iostream>
struct HumanReadable
{
    std::uintmax_t size{};
    template<typename Os> friend Os& operator<<(Os& os, HumanReadable hr)
    {
        int i{};
        double mantissa = hr.size;
        for (; mantissa >= 1024.0; mantissa /= 1024.0, ++i)
        {}
        os << std::ceil(mantissa * 10.0) / 10.0 << i["BKMGTPE"];
        return i ? os << "B (" << hr.size << ')' : os;
    }
};
int main(int argc, const char* argv[])
{
    const auto dir = argc == 2 ? std::filesystem::path{argv[1]}
                               : std::filesystem::current_path();
    for (std::filesystem::directory_entry const& entry : 
         std::filesystem::directory_iterator(dir))
        if (entry.is_regular_file())
            std::cout << entry.path().filename() << " size: "
                      << HumanReadable{entry.file_size()} << '\n';
}

가능한 출력:

"boost_1_73_0.tar.bz2" size: 104.2MB (109247910)
"CppCon 2018 - Jon Kalb “Copy Elision”.mp4" size: 15.7MB (16411990)
"cppreference-doc-20190607.tar.xz" size: 6.3MB (6531336)
"hana.hpp" size: 6.7KB (6807)

참고 항목

(C++17)
파일의 크기를 반환합니다
(함수)