如何使用C ++ 17获得以字节为单位的文件大小 [英] How to get the file size in bytes with C++17

查看:99
本文介绍了如何使用C ++ 17获得以字节为单位的文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该知道特定操作系统是否存在陷阱吗?

Are there pitfalls for specific operating systems, I should know of?

有很多重复项( 1 2 3 4 5 )这个问题,但几十年前得到了回答。在许多这些问题中,投票率很高的答案今天是错误的。

There are many duplicates (1, 2, 3, 4, 5) of this question but they were answered decades ago. The very high voted answers in many of these questions are wrong today.

  • stat.h (wrapper sprintstatf), uses syscall

tellg(),根据定义返回一个位置,但不一定是字节。返回类型不是 int

tellg(), returns per definition a position but not necessarily bytes. The return type is not int.

推荐答案

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

<filesystem> (added in C++17) makes this very straightforward.

#include <cstdint>
#include <filesystem>

// ...

std::uintmax_t size = std::filesystem::file_size("c:\\foo\\bar.txt");






如评论中所述,如果您正在计划要使用此功能确定要从文件中读取多少字节,请记住...


As noted in comments, if you're planning to use this function to decide how many bytes to read from the file, keep in mind that...


...除非文件是由您独家打开的,它的大小可以在您请求它的时间和尝试从中读取数据的时间之间进行更改。

– Nicol Bolas

...unless the file is exclusively opened by you, its size can be changed between the time you ask for it and the time you try to read data from it.
– Nicol Bolas

这篇关于如何使用C ++ 17获得以字节为单位的文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆