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

How to determine size of a huge binary file in c++

本文关键字:二进制文件 大型 c++      更新时间:2023-10-16

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

在大多数系统上,有stat()fstat()功能(不是ANSI-C的一部分,而是POSIX的一部分)。对于 Linux,请查看手册页。

编辑:对于Windows,文档在这里。

编辑:对于更便携的版本,请使用Boost库:

#include <iostream>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
int main(int argc, char* argv[])
{
  if (argc < 2)
  {
    std::cout << "Usage: tut1 pathn";
    return 1;
  }
  std::cout << argv[1] << " " << file_size(argv[1]) << 'n';
  return 0;
}
#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();

这应该有效:

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