如何使用C 17获取文件大小

How to get the file size in bytes with C++17

本文关键字:获取 文件大小 何使用      更新时间:2023-10-16

特定操作系统有陷阱吗?

这个问题有许多重复(1、2、3、4、5(,但几十年前回答了。当今许多问题中,非常高的选票答案是错误的。

来自其他(旧质量质量质量(的方法.sx

  • stat.h(包装sprintstatf(,使用syscall

  • tellg((,每个定义返回a 位置但不一定是字节。返回类型不是int

<filesystem>(在C 17中添加(使此非常简单。

#include <cstdint>
#include <filesystem>
// ...
std::uintmax_t size = std::filesystem::file_size("c:\foo\bar.txt");

如评论中所述,如果您打算使用此功能来决定从文件中读取多少个字节,请记住...

...除非您仅打开文件,否 - Nicol Bolas

c 17带来的std::filesystem,它简化了有关文件和目录的许多任务。您不仅可以快速获取文件大小,其属性,而且还可以创建新目录,通过文件进行迭代,使用路径对象。

新库为我们提供了可以使用的两个功能:

std::uintmax_t std::filesystem::file_size( const std::filesystem::path& p );
std::uintmax_t std::filesystem::directory_entry::file_size() const;

第一个功能是std::filesystem中的免费功能,第二个功能是directory_entry中的方法。

每种方法还具有过载,因为它可以抛出异常或返回错误代码(通过输出参数(。以下是解释所有可能情况的详细代码。

#include <chrono>
#include <filesystem>  
#include <iostream>
namespace fs = std::filesystem;
int main(int argc, char* argv[])
{
    try
    {
        const auto fsize = fs::file_size("a.out");
        std::cout << fsize << 'n';
    }
    catch (const fs::filesystem_error& err)
    {
        std::cerr << "filesystem error! " << err.what() << 'n';
        if (!err.path1().empty())
            std::cerr << "path1: " << err.path1().string() << 'n';
        if (!err.path2().empty())
            std::cerr << "path2: " << err.path2().string() << 'n';
    }
    catch (const std::exception& ex)
    {
        std::cerr << "general exception: " << ex.what() << 'n';
    }
    // using error_code
    std::error_code ec{};
    auto size = std::filesystem::file_size("a.out", ec);
    if (ec == std::error_code{})
        std::cout << "size: " << size << 'n';
    else
        std::cout << "error when accessing test file, size is: " 
              << size << " message: " << ec.message() << 'n';
}