如何在c ++中确定一个巨大的二进制文件的大小

时间:2014-04-04 14:07:41

标签: c++ binary

确定二进制文件的大小似乎总是涉及将整个文件读入内存。如何确定一个非常大的二进制文件的大小,这个文件的大小比内存可以大?

3 个答案:

答案 0 :(得分:6)

在大多数系统上,有stat()fstat()函数(不是ANSI-C的一部分,而是POSIX的一部分)。对于Linux,请查看man page

编辑:对于Windows,文档为here

编辑:要获得更便携的版本,请使用Boost库:

#include <iostream>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;

int main(int argc, char* argv[])
{
  if (argc < 2)
  {
    std::cout << "Usage: tut1 path\n";
    return 1;
  }
  std::cout << argv[1] << " " << file_size(argv[1]) << '\n';
  return 0;
}

答案 1 :(得分:3)

#include <cstdio>

FILE *fp = std::fopen("filename", "rb");
std::fseek(fp, 0, SEEK_END);
long filesize = std::ftell(fp);
std::fclose(fp);

或者,使用ifstream

#include <fstream>

std::ifstream fstrm("filename", ios_base::in | ios_base::binary);
fstrm.seekg(0, ios_base::end);
long filesize = fstrm.tellg();

答案 2 :(得分:-1)

这应该有效:

uintmax_t file_size(std::string path) {
  return std::ifstream(path, std::ios::binary|std::ios::ate).tellg();
}
相关问题