每个人!我有一个充满无符号字符的二维向量。现在我想将其内容保存到二进制文件中:
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);
Run Code Online (Sandbox Code Playgroud)
但是,当我读取 test.dat 时,填写一个新的二维向量,并将其条目与旧的条目进行比较。我发现写的内容和原文不一样。为什么?我写的语句有什么问题吗?您能告诉我如何以正确的方式将二维向量写入二进制文件吗?非常感谢!
#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
Run Code Online (Sandbox Code Playgroud)
那是错的。包含的数据v2D不在连续内存中。然而,v2D(它是一个向量)的每个元素都位于连续的内存中。也就是说, 包含的数据v2D[i]位于连续的内存中。
所以你应该这样做:
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);
}
Run Code Online (Sandbox Code Playgroud)
或者您可以将 C++ IOStream 用作:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4324 次 |
| 最近记录: |