如何使用C 17获取文件大小
How to get the file size in bytes with C++17
特定操作系统有陷阱吗?
这个问题有许多重复(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';
}
相关文章:
- 如何在Windows内核中获取文件大小
- 使用 C++ iOS::ate 获取错误的文件大小
- 如何使用文件系统库获取"true"文件大小?(C++17)
- 如何使用C 17获取文件大小
- HttpQueryInfo 获取文件大小
- 从CfileDialog获取文件大小
- 如何获取文件的大小
- 使用ifstream::seekg和tellg获取文件大小
- 有没有办法通过程序在特定时间获取文件部分加载内容的大小C++
- 如何获取文件大小和文件名和文件开始地址?
- 在 C# 中获取十六进制文件大小
- 如何在下载前获取文件大小
- 如何通过Windows API获取文件夹大小
- 打开文件并使用fseek获取文件大小-C++
- 在C/C++中获取文件大小、文件扩展名并将其分配到不同名称的新文件夹
- 在windows上用c++获取系统应用程序的文件大小
- 在windows中获取文件大小
- visual获取c++中的文件大小
- C++获取文件大小信息的更快方法
- 如何以C++为单位获取文件的大小?