Skip to content

Instantly share code, notes, and snippets.

@halfelf
Created September 10, 2012 07:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halfelf/3689439 to your computer and use it in GitHub Desktop.
Save halfelf/3689439 to your computer and use it in GitHub Desktop.
Reading Lines from a File in erlang
for_each_line_in_file(Name, Proc, Mode, Accum0) ->
{ok, Device} = file:open(Name, Mode),
for_each_line(Device, Proc, Accum0).
for_each_line(Device, Proc, Accum) ->
case io:get_line(Device, "") of
eof -> file:close(Device), Accum;
Line -> NewAccum = Proc(Line, Accum),
for_each_line(Device, Proc, NewAccum)
end.
% example
% A = for_each_line_in_file("complex.erl",
% fun(X, Count) -> io:fwrite("~10B: ~s", [Count, X]),
% Count + 1 end, [read], 0).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment