所以这就是我想出的。我稍微修改了您的 readdata/2 以优化附加并删除换行符。write/2 函数使用 lists:foreach/2 和 io:fwrite/3 写入文件。
-module(rwlist).
-export([read/1,write/2]).
read(FileName) ->
case file:open(FileName, [read]) of
{ok, Device} ->
readdata(Device, [])
end.
readdata(Device, Accum) ->
case io:get_line(Device, "") of
eof -> file:close(Device), lists:reverse(Accum);
Line -> readdata(Device, [(Line--"\n")|Accum])
end.
write(FileName, List) ->
case file:open(FileName, [write]) of
{ok, Device} ->
lists:foreach(fun(Line) -> writeline(Device, Line) end, List),
file:close(Device)
end.
writeline(Device, Line) -> writeline(Device, Line, os:type()).
writeline(Device, Line, {win32,_}) -> io:fwrite(Device, "~s\r\n", [Line]);
writeline(Device, Line, _) -> io:fwrite(Device, "~s\n", [Line]).
这里是测试...
57> List=rwlist:read("list").
["item 1","item 2","item 3","item 4"]
58> rwlist:write("list2", List).
ok
59> List2=rwlist:read("list2").
["item 1","item 2","item 3","item 4"]
当然,如果您只是复制文件,Dmitry 的答案会更好。