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

时间:2018-12-28 15:43:37

标签: c++ file buffer short

我创建了一个将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数组中的数据。

1 个答案:

答案 0 :(得分:1)

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