在C++中使用 CArchive 类从二进制文件中读取短数据

Read short data from binary file using CArchive class in C++

本文关键字:二进制文件 读取 数据 CArchive C++      更新时间:2023-10-16

我创建了一个应用程序,将数组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))
{
}

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

假设缓冲区是 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();