473,769 Members | 2,134 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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.qualif ication,"MCA");

CString fileName = "c:\\testdata.d at";

CFile file;
file.Open(fileN ame,CFile::mode Create | CFile::modeWrit e |
CFile::typeBina ry);
file.Write(&s,s izeof(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
Mar 30 '07 #1
10 7491

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c omwrote in
message news:uk******** ******@TK2MSFTN GP02.phx.gbl...
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]
- mv*@spam.guard. caspershouse.co m

"Nand Kishore Gupta" <Na************ **@discussions. microsoft.comwr ote in
message news:A0******** *************** ***********@mic rosoft.com...
>>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.qualif ication,"MCA");

CString fileName = "c:\\testdata.d at";

CFile file;
file.Open(fileN ame,CFile::mode Create | CFile::modeWrit e |
CFile::typeBin ary);
file.Write(&s,s izeof(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


Mar 30 '07 #2
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
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]
- mv*@spam.guard. caspershouse.co m

"Nand Kishore Gupta" <Na************ **@discussions. microsoft.comwr ote in
message news:A0******** *************** ***********@mic rosoft.com...
>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.qualif ication,"MCA");

CString fileName = "c:\\testdata.d at";

CFile file;
file.Open(fileN ame,CFile::mode Create | CFile::modeWrit e |
CFile::typeBina ry);
file.Write(&s,s izeof(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

Mar 30 '07 #3
"Ben Voigt" <rb*@nospam.nos pamwrote in message
news:eU******** *******@TK2MSFT NGP05.phx.gbl.. .
>
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c omwrote in message
news:uk******** ******@TK2MSFTN GP02.phx.gbl...
>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.
Why? The int is the first field of the struct, the second is a char array which has no
alignment restriction, so, whatever the packing, the length written on disk will be 74.

Willy.

Mar 30 '07 #4
On Fri, 30 Mar 2007 04:06:00 -0700, Nand Kishore Gupta
<Na************ **@discussions. microsoft.comwr ote:
>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.qualif ication,"MCA");

CString fileName = "c:\\testdata.d at";

CFile file;
file.Open(fileN ame,CFile::mode Create | CFile::modeWrit e |
CFile::typeBin ary);
file.Write(&s,s izeof(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
Two points:

- you need to know what endinness and size of integer the C++
compiler is using. There is no guarantee that they will be the same
for C#.

- depending on what characters are allowed in names you may also need
to pay attention to what character encoding is used at the C++ end.
For instance, Étienne has an accented character which might not
translate correctly.

If you have control over the C++ end I would suggest modifying the C++
code to write a text file, rather than a binary file. That will solve
the endianness problem and just leave you with the character encoding
problem. For simplicity a CSV file is probably best:

"1","nand","MCA "
"2","martin","P GCE"

though XML is also a possibility.

rossum

Mar 30 '07 #5

"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:eD******** ******@TK2MSFTN GP03.phx.gbl...
"Ben Voigt" <rb*@nospam.nos pamwrote in message
news:eU******** *******@TK2MSFT NGP05.phx.gbl.. .
>>
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c omwrote
in message news:uk******** ******@TK2MSFTN GP02.phx.gbl...
>>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.

Why? The int is the first field of the struct, the second is a char array
which has no alignment restriction, so, whatever the packing, the length
written on disk will be 74.
As I said, the OP's C code writes sizeof(s) bytes to disk. Padding is
included in sizeof, because sizeof is the separation between adjacent array
elements which must both be properly aligned.

If there's only one record in the file, it's a non-issue. But I was
responding to a post mentioning "read the file in 74 byte blocks".
Mar 30 '07 #6
"Ben Voigt" <rb*@nospam.nos pamwrote in message
news:ee******** ******@TK2MSFTN GP05.phx.gbl...
>
"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:eD******** ******@TK2MSFTN GP03.phx.gbl...
>"Ben Voigt" <rb*@nospam.nos pamwrote in message
news:eU******* ********@TK2MSF TNGP05.phx.gbl. ..
>>>
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c omwrote in message
news:uk****** ********@TK2MSF TNGP02.phx.gbl. ..
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.

Why? The int is the first field of the struct, the second is a char array which has no
alignment restriction, so, whatever the packing, the length written on disk will be 74.

As I said, the OP's C code writes sizeof(s) bytes to disk. Padding is included in sizeof,
because sizeof is the separation between adjacent array elements which must both be
properly aligned.

If there's only one record in the file, it's a non-issue. But I was responding to a post
mentioning "read the file in 74 byte blocks".
Oh, I see what you mean, but here the sizeof depends on the packing specified (or the
default packing). This is why I'm always trying to define my structs like this;
#pragma pack(show)
struct student
{
int roll_no;
char name[20];
char qualification[50];
};
#pragma pack(pop)
#pragma pack(show)

when writing to disk, especially when these files have to be read by "foreign" applications.
No surprises here, the size is exactly the sum of all it's elements.

Willy.
Mar 30 '07 #7

"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:%2******** *******@TK2MSFT NGP05.phx.gbl.. .
"Ben Voigt" <rb*@nospam.nos pamwrote in message
news:ee******** ******@TK2MSFTN GP05.phx.gbl...
>>
"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:eD******* *******@TK2MSFT NGP03.phx.gbl.. .
>>"Ben Voigt" <rb*@nospam.nos pamwrote in message
news:eU****** *********@TK2MS FTNGP05.phx.gbl ...

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om>
wrote in message news:uk******** ******@TK2MSFTN GP02.phx.gbl...
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.
Why? The int is the first field of the struct, the second is a char
array which has no alignment restriction, so, whatever the packing, the
length written on disk will be 74.

As I said, the OP's C code writes sizeof(s) bytes to disk. Padding is
included in sizeof, because sizeof is the separation between adjacent
array elements which must both be properly aligned.

If there's only one record in the file, it's a non-issue. But I was
responding to a post mentioning "read the file in 74 byte blocks".

Oh, I see what you mean, but here the sizeof depends on the packing
specified (or the default packing). This is why I'm always trying to
define my structs like this;
#pragma pack(show)
Did you mean to add here:
#pragma pack(push, 1)

?
struct student
{
int roll_no;
char name[20];
char qualification[50];
};
#pragma pack(pop)
#pragma pack(show)

when writing to disk, especially when these files have to be read by
"foreign" applications. No surprises here, the size is exactly the sum of
all it's elements.
That's very non-portable though, many CPUs will generate hard exceptions if
you use unaligned data. Also the compiler is allowed to reorder the
members. So it's best to serialize each element individually.
>
Willy.


Mar 30 '07 #8
"Ben Voigt" <rb*@nospam.nos pamwrote in message
news:u4******** ******@TK2MSFTN GP02.phx.gbl...
>
"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:%2******** *******@TK2MSFT NGP05.phx.gbl.. .
>"Ben Voigt" <rb*@nospam.nos pamwrote in message
news:ee******* *******@TK2MSFT NGP05.phx.gbl.. .
>>>
"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:eD****** ********@TK2MSF TNGP03.phx.gbl. ..
"Ben Voigt" <rb*@nospam.nos pamwrote in message
news:eU***** **********@TK2M SFTNGP05.phx.gb l...
>
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c omwrote in message
news:uk**** **********@TK2M SFTNGP02.phx.gb l...
>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.
>

Why? The int is the first field of the struct, the second is a char array which has no
alignment restriction, so, whatever the packing, the length written on disk will be 74.

As I said, the OP's C code writes sizeof(s) bytes to disk. Padding is included in
sizeof, because sizeof is the separation between adjacent array elements which must both
be properly aligned.

If there's only one record in the file, it's a non-issue. But I was responding to a
post mentioning "read the file in 74 byte blocks".

Oh, I see what you mean, but here the sizeof depends on the packing specified (or the
default packing). This is why I'm always trying to define my structs like this;
#pragma pack(show)

Did you mean to add here:
#pragma pack(push, 1)

?
>struct student
{
int roll_no;
char name[20];
char qualification[50];
};
#pragma pack(pop)
#pragma pack(show)

when writing to disk, especially when these files have to be read by "foreign"
applications . No surprises here, the size is exactly the sum of all it's elements.

That's very non-portable though, many CPUs will generate hard exceptions if you use
unaligned data. Also the compiler is allowed to reorder the members. So it's best to
serialize each element individually.
Agreed, you can have portability issues doing this, but this is also true when relying on
the default packing.
Note also that such issues are quite common when passing data from one platform (HW and OS)
to another, I would never use this kind of packing for "applicatio n data structures" only
when I need to pass binary data across program boundaries, and I'm never using this to pass
data across non "compatible " (HW and OS) systems.
Anyway, the only CPU I know that will generate hard exceptions is Intel's Itanium, others
like Intel's IA32, Intel 64 (X64 EM), AMD 32 and 64, all handle alignment issues in µcode
(taking a small performance hit). The Alpha CPU raises an alignment exception, which the OS
can correct or just ignore, on a per application basis, I thought Intel's Itanium did
exactly the same.
Willy.

Mar 30 '07 #9
>That's very non-portable though, many CPUs will generate hard exceptions
if you use
unaligned data. Also the compiler is allowed to reorder the members. So
it's best to serialize each element individually.
Agreed, you can have portability issues doing this, but this is also true
when relying on the default packing.
Note also that such issues are quite common when passing data from one
platform (HW and OS) to another, I would never use this kind of packing
for "applicatio n data structures" only when I need to pass binary data
across program boundaries, and I'm never using this to pass data across
non "compatible " (HW and OS) systems.
Anyway, the only CPU I know that will generate hard exceptions is Intel's
Itanium, others like Intel's IA32, Intel 64 (X64 EM), AMD 32 and 64, all
handle alignment issues in µcode (taking a small performance hit). The
Alpha CPU raises an alignment exception, which the OS can correct or just
ignore, on a per application basis, I thought Intel's Itanium did exactly
the same.
Ok, maybe not a hard exception, but the performance hit from having the OS
trap the unaligned access and emulate proper alignment is quite high.
Mar 31 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
3073
by: ishmael4 | last post by:
hello everyone! i have a problem with reading from binary file. i was googling and searching, but i just cant understand, why isnt this code working. i could use any help. here's the source code: --cut here-- typedef struct pkg_ { short int info; char* data;
50
5013
by: Michael Mair | last post by:
Cheerio, I would appreciate opinions on the following: Given the task to read a _complete_ text file into a string: What is the "best" way to do it? Handling the buffer is not the problem -- the character input is a different matter, at least if I want to remain within the bounds of the standard library.
3
8383
by: Matt Laver | last post by:
Hi, I have a binary file that I'm currently reading byte by byte using code similiar to: string FileName = @"c:\myFile.dat"; FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs);
6
5273
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
16
3752
by: Jm.GlezdeRueda | last post by:
Hi all, Im trying to read a 24bit bmp with fread, and i have some problems.. I want to read the whole structure in one time, but i dont know why, it only reads the first member well.. I have two questions.. 1- why if i change fread(bmp1, sizeof(bmp1), 1, fin); to fread(bmp1, sizeof(struct bmp), 1, fin); i have a Segment violation ??
13
3713
by: swetha | last post by:
HI Every1, I have a problem in reading a binary file. Actually i want a C program which reads in the data from a file which is in binary format and i want to update values in it. The file consists of structures of type---- struct record { int acountnum; char name; float value;
6
3529
by: efrenba | last post by:
Hi, I came from delphi world and now I'm doing my first steps in C++. I'm using C++builder because its ide is like delphi although I'm trying to avoid the vcl. I need to insert new features to an old program that I wrote in delphi and it's a good opportunity to start with c++.
8
1944
by: Bryan.Fodness | last post by:
Hello, I am having trouble writing the code to read a binary string. I would like to extract the values for use in a calculation. Any help would be great. Here is my function that takes in a string. def parseSequence(data, start):
3
11153
by: =?Utf-8?B?UmF5IE1pdGNoZWxs?= | last post by:
Hello, I'm trying to write an array of structures named myStructArray to a binary file and later on read it back. Although I could complete the entire project in C in about 2 minutes, I obviously have my head up and locked when it comes to C#. My first attempt to read such a file was something like: myBinaryReader.ReadBytes(sizeof(myStructArray));
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9997
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.