Home All Groups Group Topic Archive Search About

Reading Writing Binary data to a file

Author
16 Jun 2006 7:45 PM
RML
Hi,

I have a MFC C++ application which write the data in a structure out to a
file.  Here is the structure...

typdef struct {
   short ID;
   TCHAR Num[10];
   short x;
} TestStruct;

I then have a VB.NET app which reads the file data in using a BinaryReader. 
Here is the structure I save it to.

    <StructLayout(LayoutKind.Sequential, Pack:=1)> _
    Public Structure PartBlock_Struct
        Public ID As Short                  ' Part Identifier.  See
PARTS_STRUCT above
        <MarshalAs(UnmanagedType.ByValArray, SizeConst:=10)> _
        Public Num As String                ' Circuit Test Number.
        Public x As Short
   End Structure

When I read in the data (VB.NET app) all is find.  My problem is when I
write it back out in the VB.NET app.  I use a BinaryWriter to do this.  Here
is the code.

                bw.Write(PartBlock.ID)
                bw.Write(PartBlock.Num)
               bw.Write(PartBlock.x)

When the 1st bw.Write executes, the BinaryWritter's Position is 2, thats
good.  After the next bw.Writer runs, the Position is 13!  I would expect it
to be 12.  Because of this, the "x" value is offset by 1 byte, hence when I
read this file back in, "x" value is incorrect.

Can anyone help?

RML

Author
19 Jun 2006 11:47 PM
GhostInAK
Hello RML,

Have you popped the file open in a hex editor to see what the extraneaous
byte is?  That might give you a clue or two.

-Boo

Show quoteHide quote
> Hi,
>
> I have a MFC C++ application which write the data in a structure out
> to a file.  Here is the structure...
>
> typdef struct {
> short ID;
> TCHAR Num[10];
> short x;
> } TestStruct;
> I then have a VB.NET app which reads the file data in using a
> BinaryReader.  Here is the structure I save it to.
>
> <StructLayout(LayoutKind.Sequential, Pack:=1)> _
> Public Structure PartBlock_Struct
> Public ID As Short                  ' Part Identifier.  See
> PARTS_STRUCT above
> <MarshalAs(UnmanagedType.ByValArray, SizeConst:=10)> _
> Public Num As String                ' Circuit Test Number.
> Public x As Short
> End Structure
> When I read in the data (VB.NET app) all is find.  My problem is when
> I write it back out in the VB.NET app.  I use a BinaryWriter to do
> this.  Here is the code.
>
> bw.Write(PartBlock.ID)
> bw.Write(PartBlock.Num)
> bw.Write(PartBlock.x)
> When the 1st bw.Write executes, the BinaryWritter's Position is 2,
> thats good.  After the next bw.Writer runs, the Position is 13!  I
> would expect it to be 12.  Because of this, the "x" value is offset by
> 1 byte, hence when I read this file back in, "x" value is incorrect.
>
> Can anyone help?
>
> RML
>