[英]how to efficiently read a binary file into a vector C++
I need to read a large binary file (~1GB) into a std::vector<double>
. 我需要将一个大的二进制文件(~1GB)读入
std::vector<double>
。 I'm currently using infile.read
to copy the whole thing into a char *
buffer (shown below) and I currently plan to convert the whole thing into doubles
with reinterpret_cast
. 我目前正在使用
infile.read
将整个内容复制到char *
缓冲区(如下所示),我目前计划使用reinterpret_cast
将整个内容转换为doubles
。 surely there must be a way to just put the doubles
straight into the vector
? 肯定有一种方法可以将
doubles
直接放入vector
吗?
I'm also not sure about the format of the binary file, the data was produced in python so it's probably all floats 我也不确定二进制文件的格式,数据是在python中生成的,所以它可能都是浮点数
ifstream infile(filename, std--ifstream--binary);
infile.seekg(0, infile.end); //N is the total number of doubles
N = infile.tellg();
infile.seekg(0, infile.beg);
char * buffer = new char[N];
infile.read(buffer, N);
Assuming the entire file is double, otherwise this wont work properly. 假设整个文件是双倍的,否则这将无法正常工作。
std::vector<double> buf(N / sizeof(double));// reserve space for N/8 doubles
infile.read(reinterpret_cast<char*>(buf.data()), buf.size()*sizeof(double)); // or &buf[0] for C++98
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.