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);
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
That is wrong. The data contained by
v2Dis NOT in contiguous memory. However, each element ofv2D(which is a vector) is in contiguous memory. That is, the data contained byv2D[i]is in contiguous memory.So you should do this:
Or you can use C++ IOStream as: