Frage

To determine a size of a binary file seems to always involve read the whole file into memory. How do I determine the size of a very large binary file which is known way bigger than the memory can take?

War es hilfreich?

Lösung

On most systems, there's stat() and fstat() functions (not part of ANSI-C, but part of POSIX). For Linux, look at the man page.

EDIT: For Windows, the documentation is here.

EDIT: For a more portable version, use the Boost library:

#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;
}

Andere Tipps

#include <cstdio>

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

Or, use ifstream:

#include <fstream>

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

This should work:

uintmax_t file_size(std::string path) {
  return std::ifstream(path, std::ios::binary|std::ios::ate).tellg();
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top