使用streamsize为阵列的大小不起作用
我不知道如何使用std::streamsize
来创建一个数组。使用streamsize为阵列的大小不起作用
// determine file size
file.ignore(std::numeric_limits<std::streamsize>::max());
std::streamsize length = file.gcount();
file.clear();
file.seekg(0, std::ios_base::beg);
// read data into buffer
std::array<char, length> buffer;
file.read(buffer.data(), length);
// copy the game into memory
std::copy(buffer.begin(), buffer.end(), memory.begin() + 0x200);
错误(德国翻译)
表达式必须是一个恒定值
没有人有解决这个问题的任何想法?任何帮助表示赞赏!
只能将constexpr值作为模板参数传递,在这种情况下显然不可能,因为只有在运行时才知道大小。
这里的底层问题是,您使用的工具是错误的工具:std::array
封装了一个静态分配的数组,其大小必须在编译时已知。如果您需要动态分配,请使用std::vector
。
对于std::vector
和std::array
之间更深入的比较看std::vector versus std::array in C++
哦,那么它是有道理不能使用std :: array,谢谢:) – Urasam
你并不需要使用file.ignore()
,您可以使用file.seekg()
获得文件大小:
// determine file size
file.seekg(0, std::ios_base::end);
std::streamsize length = file.tellg();
file.seekg(0, std::ios_base::beg);
或者,只是使用特定于平台的API函数,例如Windows上的GetFileSize()
或Linux(或equivilents)上的stat()
。
也就是说,std::array
是一个固定长度的数组,你必须在编译时指定它的大小。在运行时动态分配,使用std::vector
代替:
// read data into buffer
std::vector<char> buffer;
buffer.resize(length);
file.read(buffer.data(), length);
或者,干脆直接读取文件到目标存储,并完全避免临时缓冲区:
// read game file into memory
file.read(memory.begin() + 0x200, length);
或者,甚至跳过检索文件大小在所有:
// read game file into memory
std::copy(
std::istreambuf_iterator<char>(file),
std::istreambuf_iterator<char>(),
memory.begin() + 0x200
);
在任何情况下,一定要注意内存溢出!确保memory
足够大以容纳整个file
数据。
感谢您的不同方法! 最后两个有很大的区别吗?比其他的更好(例如在性能上) – Urasam
我认为做大块读取比单字节读取具有更好的性能。但使用探查器来确保。 –
不要使用数组,请使用矢量。 –