[erlang-questions] Reading fixed structures from file
Dave Smith
dizzyd@REDACTED
Sat Mar 1 20:31:15 CET 2008
On Sat, Mar 1, 2008 at 11:54 AM, Gleb Peregud <gleber.p@REDACTED> wrote:
> Hello.
>
> I have one simple question regarding reading a fixed structure from files.
>
> Let say i have a binary file filled with sequence of fixed length
> structures. Each structure is of the form:
>
> struct {
> int32 key,
> int64 adr,
> char type
> };
>
> File was written at x86 platform, hence it is little-endian. I use R12B
>
> Is the following way the best way to read whole file to the list:
>
> scan_file(Binary) ->
> scan_file(0, Binary, []).
> scan_file(N, <<>>, List) ->
> list:reverse(List);
> scan_file(N, Binary, List) ->
> <<
> Key:4/little-integer-unit:8,
> Adr:8/little-integer-unit:8,
> Type:1/little-integer-unit:8,
> Rest/binary
> >> = Binary,
> Obj = {N, Type, Adr, Key},
> scan_file(N+1, Rest, [Obj | List]).
>
> Code was not tested.
I'm pretty sure you code would be fine that way. Personally, I would
do something like:
scan_file(N, <<>>, List) ->
lists:reverse(List);
scan_file(N, <<Key:32/little-integer, Addr:64/little-integer,
Type:8/little-integer, Rest/binary>>, List) ->
scan_file(N+1, Rest, [{N, Type, Addr, Key} | List]).
I personally feel that reads a little clearer since it's in bits and
you don't have to do clever adjustments in your head when reading the
code.
My $0.02 (and with the dollar declining, worth less every day!) :)
D.
More information about the erlang-questions
mailing list