如何将二维向量写入二进制文件? [英] How to write a 2D vector into a binary file?

查看:32
本文介绍了如何将二维向量写入二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家!我有一个充满无符号字符的二维向量.现在我想将其内容保存到一个二进制文件中:

everyone! I have a 2D vector filled with unsigned chars. Now I want to save its contents into a binary file:

std::vector<std::vector<unsigned char> > v2D(1920, std::vector<unsigned char>(1080));

// Populate the 2D vector here
.....

FILE* fpOut;

// Open for write
if ( (err  = fopen_s( &fpOut, "e:\test.dat", "wb")) !=0 )
{   
   return;
}

// Write the composite file
size_t nCount = 1920 * 1080 * sizeof(unsigned char);
int nWritten = fwrite((char *)&v2D[0][0], sizeof(unsigned char), nCount, fpOut);

// Close file
fclose(fpOut);

但是,当我读取 test.dat 时,填充一个新的 2D 向量,并将其条目与旧的条目进行比较.我发现写的内容和原文不一样.为什么?我的 write 语句有什么问题?你能告诉我如何以正确的方式将二维向量写入二进制文件吗?非常感谢!

But, when I read test.dat, fill in a new 2D vector, and compare its entries with old ones. I find that the written contents are not the same as the original. Why? What wrong with my write statement? Would you please tell me how to write a 2D vector into a binary file in a right way? Thank you very much!

    #define LON_DATA_ROWS 1920
    #define LON_DATA_COLS 1080

    std::vector<std::vector<float> > m_fLon2DArray(LON_DATA_ROWS, std::vector<float>(LON_DATA_COLS));

    std::ifstream InputFile;

    int nSizeOfLonData = TOTAL_LON_ELEMENTS * sizeof(float);

    std::vector<char> vLonDataBuffer(nSizeOfLonData);

    // Open the file
    InputFile.open(m_sNorminalLonLatFile.c_str(), ios::binary);

    // Unable to open file pszDataFile for reading
    if ( InputFile.fail() )
       return false;

    // Read longitude data buffer
    InputFile.read(&vLonDataBuffer[0], nSizeOfLonData);

    // Close the file object
    InputFile.close();

    // Populate the longitude 2D vector
    for (unsigned i = 0; i < LON_DATA_ROWS; i++) 
    {   
        memcpy(&m_fLon2DArray[i][0], &vLonDataBuffer[(i * LON_DATA_COLS) * sizeof(float)], LON_DATA_COLS * sizeof(float));
    }

    // Some operation put here

    // Write the results to a binary file

推荐答案

那是错误的.v2D 包含的数据不在连续内存中.然而,v2D(它是一个向量)的每个元素都在连续的内存中.即v2D[i]包含的数据在连续内存中.

That is wrong. The data contained by v2D is NOT in contiguous memory. However, each element of v2D (which is a vector) is in contiguous memory. That is, the data contained by v2D[i] is in contiguous memory.

所以你应该这样做:

int nWritten = 0;
for(size_t i = 0; i < v2D.size(); i++ )
{
   if ( v2D[i].size() > 0 )
     nWritten += fwrite(&v2D[i][0], sizeof(unsigned char), v2D[i].size(), fpOut);
}

或者您可以将 C++ IOStream 用作:

Or you can use C++ IOStream as:

std::ofstream file("E:\test.data", std::ofstream::binary);
for(size_t i = 0; i < v2D.size(); i++ )
{
    if ( v2D[i].size() > 0 )
    {
       const char* buffer = static_cast<const char*>(&v2D[i][0]);
       file.write(buffer, v2D[i].size());
    }
}

这篇关于如何将二维向量写入二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆