Writing binary data in managed C++

  • Thread starter Thread starter Peter Steele
  • Start date Start date
P

Peter Steele

I have a managed C++ project that contains a simple structure:

struct
{
<multiple members>
} mydata;

I want to write the contents of this structure out to disk retaining the
exactly 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?
 
John, here's what I came up with. Assuming we have a simple struct as
follows:



struct

{

...

} X;



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,
FileAccess::Write);

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 = bytes;

bw->Write(gcbytes);

bw->Flush();

bw->Close();



What I don't like about this solution is that it duplicates the entire
structure. Can the data be output directly without this duplication?



Peter
 
You can write your struct in BinaryFormat. But if you expect it should write
as you use to write in Native C or C++ with fopen(), and fwrite(), or
open(), and write(), functions then you can not. But you can use
BinaryWriter class, it has many overloaded methods of write, which can write
your struct. Make two methods in your struct Read and Write, or Load and
Save as per your choice, and write all the types with by passing
BinaryWriter instance to these methods. This will not write any headers by
the way. for example. string: S"ABCDE", will write 05, 41, 42, 43, 44, 45
(all in hex code) in Bytes. first byte is the length of your string. Int32
will write four bytes.

Good Luck.
 
Back
Top