首页 > 解决方案 > 使用 C++ 中的 CArchive 类从二进制文件中读取短数据

问题描述

我创建了一个将short数组存储到文件中的应用程序。使用CArchive class

保存数据的代码

CFile objFile(cstr, CFile::modeCreate | CFile::modeWrite);
CArchive obj(&objFile, CArchive::store);

obj << Number;  //int
obj << reso;    //int
obj << height;  //int
obj << width;   //int
int total = height * width;
for (int i = 0; i < total; i++)
    obj << buffer[i];//Short Array

这是我用来将数据保存在文件中的代码片段。

现在我想使用CArchive.

我试图用fstream.

std::vector<char> buffer(s);
if (file.read(buffer.data(), s))
{

}

但是上面的代码并没有给我保存的相同数据。那么,任何人都可以告诉我如何使用或任何其他函数获取short数组中的数据。CArchive

标签: c++filebuffershort

解决方案


假设缓冲区是一个 SHORT 数组,加载数据的代码可以写成:

CFile objFile(cstr, CFile::modeRead);
CArchive obj(&objFile, CArchive::load);

obj >> Number;  //int
obj >> reso;    //int
obj >> height;  //int
obj >> width;   //int

int total = height * width;

//release the old buffer if needed... e.g: 
if( buffer ) 
    delete[] buffer;

//allocate the new buffer 
buffer = new SHORT [total];

for (int i = 0; i < total; i++) {
    obj >> buffer[i];
}

obj.Close();
objFile.Close();

推荐阅读