[erlang-questions] Reading fixed structures from file
Gleb Peregud
gleber.p@REDACTED
Sat Mar 1 22:37:35 CET 2008
Thanks a lot.
imho my code is more readable :) But it's matter of taste.
Nevertheless, to avoid confusion, i'll ask explicitly:
Key:4/little-integer-unit:8
matches four integers each having 8 bits, right?
On 3/1/08, Dave Smith <dizzyd@REDACTED> wrote:
> 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.
>
--
Gleb Peregud
http://gleber.pl/
"Only two things are infinite, the universe and human stupidity, and
I'm not sure about the former."
-- Albert Einstein
More information about the erlang-questions
mailing list