C++ 在内存中加载二进制文件并获取对象

标签 c++ buffer binaryfiles ifstream

我有一个二进制文件,我在其中保存了以下变量数百万次:

  • x 大小的浮点 vector
  • 两个无符号整数

目前我正在使用 ifstream 打开和读取文件,但我想知道是否可以通过将整个文件加载到内存中并减少 I/O 来加快执行时间。

如何将文件加载到内存中,然后将其转换为我想要的变量?使用 ifstream 这很容易完成,但我不知道如何缓冲它然后提取数据。

这是我用来保存数据的代码:

osfile.write(reinterpret_cast<const char*> (&sz), sizeof(int));// Size of vector
osfile.write(reinterpret_cast<const char*> (&vec[0]), sz*sizeof(float));
osfile.write(reinterpret_cast<const char*> (&a), sizeof(unsigned int));
osfile.write(reinterpret_cast<const char*> (&b), sizeof(unsigned int));

最佳答案

我猜你的写过程中缺少某些东西,因为你的写流中缺少 vector 的大小......

size_t size = vec.size();
osfile.write(reinterpret_cast<const char*> (&size), sizeof(size_t));
osfile.write(reinterpret_cast<const char*> (&vec[0]), vec.size()*sizeof(float));

osfile.write(reinterpret_cast<const char*> (&i), sizeof(unsigned int));
osfile.write(reinterpret_cast<const char*> (&i), sizeof(unsigned int));

然后你可以将全局文件缓冲区加载到内存中: Read whole ASCII file into C++ std::string

然后,将加载的缓冲区传递给 istringstream iss; 对象

然后,以与编写流相同的方式读取流(流方法):

float tmp;
size_t size_of_vector;
// read size of vector
iss >> size_of_vector;
// allocate once
vector<float> vec(size_of_vector);
// read content
while(size_of_vector--)
{
    iss >> tmp;
    vec.push_back(tmp);
}
// at the end, read your pair of int
unsigned int i1,i2;
iss >> i1;
iss >> i2;

编辑:打开/读取流时,您仍然需要注意二进制与字符的考虑......

关于C++ 在内存中加载二进制文件并获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34292209/

相关文章:

c++ - 为什么 istream_iterator<string>(ifstream ("test.txt")) 会导致错误?

c++ - 如何将 GUID 和 64 位时间戳散列到另一个 GUID

c++ - 右值或左值 (const) 引用参数

c++ - 有条件地并行填充 vector

c - 删除文件之前需要fsync吗?

python - 更新 Python Pickle 文件

c - C 中 get 的缓冲区溢出

c - C运算中的Socket客户端

serialization - 了解 Ada 如何序列化记录

C++ mpz_class 和二进制文件