P
P
prog3232014-04-23 19:21:27
Erlang
prog323, 2014-04-23 19:21:27

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

1 answer(s)
R
Rsa97, 2014-04-23
@prog323

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.

You can write it like this:
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 question

Ask a Question

731 491 924 answers to any question