c++ - 如何使用 C++ 获取文件的实际大小?

标签 c++ file size byte

我正在使用 tellg() 来获取一些文件的大小,对于这个项目来说获取文件的真实/正确大小非常重要。现在我有点担心,因为读到 tellg() 不能完美地工作,但它可能会得到错误的大小,可能比实际大小大。例如这里:tellg() function give wrong size of file?

如何获得正确的尺寸??或者 tellg 不是很好吗?

这是我使用 tellg() 的代码:

streampos begin,end;
    ifstream file_if(cpd_file, ios::binary);
    begin = file_if.tellg();
    file_if.seekg(0, ios::end);
    end = file_if.tellg();
    file_if.close();
    size = end - begin;

最佳答案

要获取文件的大小和其他信息,如创建和修改时间、所有者、权限等,您可以使用 stat() 函数。

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat s;
if (stat("path/to/file.txt", &s)) {
    // error
}

printf("filesize in bytes: %u\n", s.st_size);

文档:

关于c++ - 如何使用 C++ 获取文件的实际大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40398755/

相关文章:

python - 尝试在 python 中的文件对象上调用 readline() 但它正在暂停

emacs - 如何更改分屏 emacs 窗口的大小?

c++ - 当它只有 4 个字节时,float 怎么可能容纳 3.4E38 这样大的数字呢?

c++ - CGAL 修改现有的多边形

c++ - 退出后从 C++ 程序永久设置环境变量

C++:引用 "out of scope"对象

c++ - 正则表达式模式的反向应用程序使用

java - 写入一个已经存在的文件

java - 奇怪的 JFrame 大小

Java删除超过N天的文件