Jon*_*ein 93 c++ filesize c++-standard-library c++17
我应该知道,特定操作系统是否存在陷阱?
有很多重复(1,2,3,4,5这个问题),但他们在几十年前进行了解答。在许多这些问题中,投票率很高的答案今天是错误的。
stat.h(wrapper sprintstatf),使用syscall
tellg(),根据定义返回一个位置,但不一定返回bytes。返回类型不是int。
Hol*_*Cat 119
<filesystem>(在C ++ 17中添加)使此操作非常简单。
#include <cstdint>
#include <filesystem>
// ...
std::uintmax_t size = std::filesystem::file_size("c:\\foo\\bar.txt");
Run Code Online (Sandbox Code Playgroud)
如评论中所述,如果您打算使用此功能来决定从文件中读取多少字节,请记住...
...除非文件是由您专门打开的,否则可以在请求文件的时间与尝试从文件中读取数据的时间之间更改文件的大小。
–尼科尔·波拉斯(Nicol Bolas)
GOV*_*XIT 27
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;
Run Code Online (Sandbox Code Playgroud)
中的第一个函数是自由函数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';
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6026 次 |
| 最近记录: |