Reading terms from a file.

Martin J. Logan <>
Wed Nov 21 18:43:29 CET 2001


Hello,
    Does anyone have any suggestions on the best way to read erlang
terms from a file. I am using io_lib:fread and parsing the data I get.
This rather simple meathod has worked well for me in the past because I
was only doing simple things with files.  I would like to read in
complex erlang terms such as those found in the .app and .rel files.

The way I do things right now is short but too simple.

%% read/2: Reads the commands file
%% Arg1: The list of services.
%% Arg2: IoDevice - The io device process

read([eof|Service], IoDevice) ->
    Service;
read(Service, IoDevice) ->
    String = io:get_line(IoDevice, ""),
    Line = normalize(io_lib:fread("~s ~a ~a ~d", String)),
    read([Line|Service], IoDevice).

normalize({ok, Line, LeftOver}) ->
    ArgList = string:tokens(chop(LeftOver, "\n"), " "),
    list_to_tuple(lists:append(Line, [ArgList]));
normalize({ok, Line}) ->
    list_to_tuple(lists:append(chop(Line, "\n"), [[]]));
normalize(eof) ->
    eof.

This allows me to read the static elements that I have in the beginning
of each line and then an abitrary number of leftover elements are put
into a list and added to the list of static elements. so I am left with
a ["string", atom, atom, digit, [any number of elements]]. This is fine
but if I could efficiantly grab erlang terms from the file I could
imrove the logic of my application without making it ugly.


            Thanks,
             Martin Logan.





More information about the erlang-questions mailing list