我有一个名为TOWRITE的结构。我想将结构内容写入文件。但是一件事是结构成员的大小是固定的。这取决于从另一个来源接收的数据。是否可以通过简单的方式编写结构。请引用以下代码段。

谢谢

typedef struct TOWRITE
{
   DWORD dwHeader;
   WORD datacount;
   LPBYTE lpData;
   WORD checksum;
}

TOWRITE towrite;
ZeroMemory( &towrite, sizeof( TOWRITE ));
towrite.lpData = (LPBYTE) new BYTE[256];

towrite.dwHeader = 0xF1F1E1E1;
towrite.datacount = 256;
towrite.cheksum = 3849;
CopyMemory( towrite.lpData, szTemp, 256 );

.....

.....

.....

f.write( (LPBYTE)&towrite, sizeof(TOWRITE) );
....
....
....
....

最佳答案

typedef struct TOWRITE
{
   DWORD dwHeader;
   WORD datacount;
   WORD checksum;
   LPBYTE lpData; //Put the ptr at the end
}

// - sizeof(LPBYTE) avoid the ptr @ to be written
f.write( (LPBYTE)&towrite, sizeof(TOWRITE) - sizeof(LPBYTE));

// write the ptr data.
// sorry I don't know windows C.
// fix the size of the array element :)
f.write( towrite.lpData, towrite.datacount * sizeof(????));

关于c++ - C/C++中的未固定结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12121602/

10-11 00:20