How to write unmanaged binary data in a managed C++ app?
Posted on 2004-09-30
I want to write the contents of a struct out to disk retaining the exact binary data without any additional header information, and of course be able to later read it back in. What's the best way to accomplish this? Here's what I came up with. Assuming we have a simple struct as follows:
whose members have been initialized in some manner, then the following code
can be used to dump the bytes of this structure:
FileStream* fs = new FileStream("C:\\data.bin", FileMode::Create,
BinaryWriter* bw = new BinaryWriter(fs);
char* bytes = (char*)&X;
char gcbytes __gc = new char __gc[sizeof X];
for (int i = 0; i < sizeof X; i++) gcbytes[i] = bytes[i];
What I don't like about this solution is that it duplicates the entire
structure. Can the data be output directly without this duplication?