Preferred way to parse a custom binary flat file?

I have a flat file generated by program C. Each entry in the file consists of a fixed-length header followed by data. The header contains a field indicating the size of the following data. My ultimate goal is to write a C # /. NET program to request this flat file, so I'm looking for the most efficient way to read the file using C #.

I am having trouble finding the .NET equivalent of line 7 in the following code. As far as I can tell, I need to issue several readings (one for each header field using BinaryReader), and then release one read to get the data following the header. I am trying to learn how to analyze records in two read operations (one is read to get a fixed-length header, and the second is read to get the following data).

This is the C code I'm trying to duplicate using C # /. NET:

struct header header; /* 1-byte aligned structure (48 bytes) */
char *data;

FILE* fp = fopen("flatfile", "r");
while (!feof(fp))
{
  fread(&header, 48, 1, fp);
  /* Read header.length number of bytes to get the data. */
  data = (char*)malloc(header.length);
  fread(data, header.length, 1, fp);
  /* Do stuff... */
  free(data);
}

This is the C header structure:

struct header
{
    char  id[2];
    char  toname[12];
    char  fromname[12];
    char  routeto[6];
    char  routefrom[6];
    char  flag1;
    char  flag2;
    char  flag3;
    char  flag4;
    char  cycl[4];
    unsigned short len;
};

I came up with this C # object to represent the C header:

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi, Size = 48)]
class RouterHeader
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
    char[] Type;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
    char[] To;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
    char[] From;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
    char[] RouteTo;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
    char[] RouteFrom;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    char[] Flags;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    char[] Cycle;

    UInt16 Length;
}
+5
source share
5 answers

Hans Passant, . , , , .

0

, Stream.Read ( , , , , ), Stream.Read, ( , , ). , , ( ).

, StructLayout - .

+2

union, , (, ), , .

StructLayouts FieldOffsets .

# . , BinaryReader (< 40) .

0

( ), . , . -, , , . , String char[], .

: , 2.0, ? , . / , , .

0

My desire was to read the data in an array and then collect the data object accordingly, using shifts and adding words, words, etc. to the words. I have some utility classes for handling such things.

0
source

All Articles