Re: reading a C++ structure from a binary file using C#




"Nicholas Paldino [.NET/C# MVP]" <mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx> wrote in
message news:uklz82tcHHA.4260@xxxxxxxxxxxxxxxxxxxxxxx
Nand,

In order to do this in .NET, I would read from the file in 74 byte
blocks (4 + 20 + 50). Then, I would call the static ToInt32 method on the

The C++ code used sizeof(s)... you must print this value out from C++. It
is unlikely to be 74, since the structure contains an int member which
prefers 4-byte alignment... so I think two bytes of padding is added by the
C++ compiler and the record spacing will be 76 bytes. But check it, because
it pragma pack was used several different values would be possible.

BitConverter class to get the roll_no field. Then you can use the
Encoding instance returned by the static ASCII property on the Encoding
class to get an encoding which you can use to convert the remaning 70
bytes into strings (by calling the GetString method).

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx

"Nand Kishore Gupta" <NandKishoreGupta@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in
message news:A07589A4-BD1C-495E-AA5B-ED2BF0C5E91F@xxxxxxxxxxxxxxxx
I have a binary file created using C++ that contains an object of the
structure:

struct student
{
int roll_no;
char name[20];
char qualification[50];
};

the following code is used to create and write to the file:

void WriteToFile()
{
student s;
s.roll_no=1;
strcpy(s.name,"nand");
strcpy(s.qualification,"MCA");

CString fileName = "c:\\testdata.dat";

CFile file;
file.Open(fileName,CFile::modeCreate | CFile::modeWrite |
CFile::typeBinary);
file.Write(&s,sizeof(s));
}

Now, I want to read the contents of this binary file (testdata.dat) using
a
C# program and store that in a C# structure. Can any body suggest me how
to
do this. Sample code would be highly appreciated.

Thanks

--
Nand Kishore Gupta




.



Relevant Pages


Loading