【问题标题】:Read short data from binary file using CArchive class in C++使用 C++ 中的 CArchive 类从二进制文件中读取短数据
【发布时间】:2018-12-28 15:43:36
【问题描述】:

我创建了一个将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

这是我用来将数据保存在文件中的代码 sn-p。

现在我想使用CArchive 打开那个文件。

我已尝试使用 fstream 打开它。

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

}

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

【问题讨论】:

    标签: c++ file buffer short


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-04
      • 2011-11-22
      • 1970-01-01
      • 2022-01-06
      • 2015-06-27
      • 2015-04-23
      • 2018-01-16
      • 1970-01-01
      相关资源
      最近更新 更多