Reading terms from a file.

Happi <>
Wed Nov 21 18:45:32 CET 2001



----- Original Message -----
From: "Martin J. Logan" <>
> Hello,
>     Does anyone have any suggestions on the best way to read erlang
> terms from a file.

Why not try
 file:consult(Filename)

Quoting the documentation:
  Opens file Filename and reads all the Erlang terms in it. Returns one of
the following:


    {ok, TermList}
    The file was successfully read.

    {error, Atom}
    An error occurred when opening the file or reading it. The Atom is a
Posix error code. See the description of open/2 for a list of typical error
codes.

    {error, {Line, Mod, Term}}
    An error occurred when interpreting the Erlang terms in the file. Use
the format_error/1 function to convert the three-element tuple to an English
description of the error.

/Erik

> 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