我正在使用 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/