Namespaces
Variants

std::filesystem:: file_size

From cppreference.net
헤더 파일에 정의됨 <filesystem>
(1) (C++17부터)
(2) (C++17부터)

만약 p 가 존재하지 않으면, 오류를 보고합니다.

일반 파일의 경우 p , POSIX stat 으로 얻은 구조체의 st_size 멤버를 읽는 것처럼 결정된 크기를 반환합니다 (심볼릭 링크는 따릅니다).

디렉토리(그리고 일반 파일이나 심볼릭 링크가 아닌 다른 파일들)의 크기를 결정하려는 시도의 결과는 구현체 정의입니다.

비예외 오버로드는 오류 발생 시 static_cast < std:: uintmax_t > ( - 1 ) 를 반환합니다.

목차

매개변수

p - 검사할 경로
ec - non-throwing 오버로드에서 오류 보고를 위한 출력 매개변수

반환값

파일의 크기(바이트 단위).

예외

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

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

예제

#include <cmath>
#include <filesystem>
#include <fstream>
#include <iostream>
namespace fs = std::filesystem;
struct HumanReadable
{
    std::uintmax_t size{};
private:
    friend std::ostream& operator<<(std::ostream& os, HumanReadable hr)
    {
        int o{};
        double mantissa = hr.size;
        for (; mantissa >= 1024.; mantissa /= 1024., ++o);
        os << std::ceil(mantissa * 10.) / 10. << "BKMGTPE"[o];
        return o ? os << "B (" << hr.size << ')' : os;
    }
};
int main(int, char const* argv[])
{
    fs::path example = "example.bin";
    fs::path p = fs::current_path() / example;
    std::ofstream(p).put('a'); // create file of size 1
    std::cout << example << " size = " << fs::file_size(p) << '\n';
    fs::remove(p);
    p = argv[0];
    std::cout << p << " size = " << HumanReadable{fs::file_size(p)} << '\n';
    try
    {
        std::cout << "Attempt to get size of a directory:\n";
        [[maybe_unused]] auto x_x = fs::file_size("/dev");
    }
    catch (fs::filesystem_error& e)
    {
        std::cout << e.what() << '\n';
    }
    for (std::error_code ec; fs::path bin : {"cat", "mouse"})
    {
        bin = "/bin"/bin;
        if (const std::uintmax_t size = fs::file_size(bin, ec); ec)
            std::cout << bin << " : " << ec.message() << '\n';
        else
            std::cout << bin << " size = " << HumanReadable{size} << '\n';
    }
}

가능한 출력:

"example.bin" size = 1
"./a.out" size = 22KB (22512)
Attempt to get size of a directory:
filesystem error: cannot get file size: Is a directory [/dev]
"/bin/cat" size = 50.9KB (52080)
"/bin/mouse" : No such file or directory

참고 항목

일반 파일의 크기를 절단 또는 제로 필로 변경
(함수)
(C++17)
파일 시스템에서 사용 가능한 여유 공간 확인
(함수)
디렉토리 엔트리가 참조하는 파일의 크기 반환
( std::filesystem::directory_entry 의 public 멤버 함수)