Search code examples
c++fstreamstdarray

C++ How to choose file size as array size


I can't use file size as array size, because it should be a constant. But I made it constant.

ifstream getsize(dump, ios::ate);
const int fsize = getsize.tellg(); // gets file size in constant variable
getsize.close();

byte dumpArr[fsize] // not correct
array<byte, fsize> dumpArr // also not correct
byte *dumpArr = new byte[fsize]; // correct, but I can't use dynamic array

I need to create std::array with the file size.


Solution

  • You need a compile-time constant to declare arrays so you have two options:

    • Give up the idea to create an array and use a std::vector instead:
      std::ifstream file("the_file");
      std::vector<std::uint8_t> content(std::istreambuf_iterator<char>(file),
                                        std::istreambuf_iterator<char>{});
      
    • If the file you want to read isn't supposed to change after you've compiled the program, make the file a part of the build system. Example makefile:
      program: source.cpp filesize.h
          g++ -o program source.cpp
      
      filesize.h: the_file
          stat --printf '#pragma once\n#define FILESIZE %sULL\n' the_file > header.h
      
      ... and use FILESIZE inside source.cpp to declare your array.