C++でファイルサイズを取得する方法

ファイルのサイズを取得するには、std::filesystemライブラリのfile_size関数が使えます。以下に例を示します。

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    fs::path filePath = "example.txt";
    
    try {
        uintmax_t fileSize = fs::file_size(filePath);
        std::cout << "File size: " << fileSize << " bytes" << std::endl;
    } catch (const fs::filesystem_error& ex) {
        std::cout << "Error: " << ex.what() << std::endl;
    }
    
    return 0;
}

上記の例では、std::filesystemライブラリのfile_size関数を使用してファイルのサイズを取得し、それをプリントアウトしています。なお、std::filesystemを使用するには、C++17以降のコンパイラとライブラリサポートが必要です。

bannerAds