Answer the question
In order to leave comments, you need to log in
How to read file.txt into an array in erlang, and then write the array to a file?
How to read file.txt into an array in erlang, and then write the array to a file?
Each element of the array must be equal to a line in the file.
The lines of the file are separated by \r\n
Answer the question
In order to leave comments, you need to log in
Read something like this:
read_file_by_lines(Name, Mode, Array) ->
{ok, Device} = file:open(Name, Mode),
read_each_line(Device, []).
read_each_line(Device, Accum) ->
case io:get_line(Device, "") of
eof -> file:close(Device), array:from_list(lists:reverse(Accum));
Line -> read_each_line(Device, [Line | Accum])
end.
write_file_by_lines(Name, Mode, Array) ->
{ok, Device} = file:open(Name, Mode),
lists:foreach(
fun(Line) -> io:write(Device, Line)
end,
array:to_list(Array)),
file:close(Device).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question