问题描述
大家!
我有一个二维向量,里面填充了无符号字符。现在,我想将其内容保存到二进制文件中。
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向量,并将其输入与旧的。我发现书面内容与原始内容不同。为什么?我的写语句有什么问题?您能告诉我如何以正确的方式将2D向量写入二进制文件吗?
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.
因此,您应该这样做:
So you should do this:
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());
}
}
这篇关于如何将2D向量写入二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!