Repeated use of io:fread fails

Matthias Lang <>
Fri Oct 25 13:33:48 CEST 2002


Roger Price writes:
 > I placed three integers into a file
 > 
 >    echo " 7 11 13" > /tmp/test
 > 
 > and then tried to read the first two with the program
 > 
 > f(File) -> {ok,Stream}=file:open(File,read),
 >            X=io:fread(Stream,'',"~d"),
 >            %% ...a comment...
 >            Y=io:fread(Stream,'',"~d"),
 >            file:close(Stream),
 >            io:format("X=~p.  Y=~p.~n", [X,Y]) .
 > 
 > but the result is
 > 
 > 23> f("/tmp/test") .
 > X={ok,[7]}.  Y={error,fread}.
 > ok

This looks like a bug in file_io_server.erl. Specifically,
get_until_loop/5 seems to insist on reading more input from the file
even when it has old input it hasn't consumed yet. There doesn't
appear to be a clause to consume the buffered input.

Suggested workaround for your problem:

   f() -> f("/tmp/test").
   f(File) ->
        {ok,Stream}=file:open(File, [read]),
        Line = io:get_line(Stream, ""),
        {ok, [X], More} = io_lib:fread("~d", Line),
        %% ...a comment...
        {ok, [Y], _} = io_lib:fread("~d", More),
        file:close(Stream),
        {X, Y}.

Aside: your calls to file:open and io:fread both contain type
errors. '' is an atom, not a list.

Matthias




More information about the erlang-questions mailing list