如何读取文件的内容在Erlang? [英] how to read the contents of a file In Erlang?

查看:75
本文介绍了如何读取文件的内容在Erlang?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以这样做:

readlines(FileName) ->
    {ok, Device} = file:open(FileName, [read]),
    get_all_lines(Device, []).

get_all_lines(Device, Accum) ->
    case io:get_line(Device, "") of
        eof  -> file:close(Device), Accum;
        Line -> get_all_lines(Device, Accum ++ [Line])
    end.

:是否有一个班轮BIF可以做到这一点?

: Is there a one liner BIF that can do this too?

推荐答案

file: read_file / 1 是您要查找的内容。只是为了教学目的, Accum ++ [Line] 是不好的做法。问题是复制了 ++ 的左参数,右键也被使用。在您的代码中,您将在每次迭代中复制更大和更大的部分。解决方案是列表:reverse(Line,Accum)而不是返回列表:reverse(Accum) eof 分支(或 [Line | Accum] 列表:append(lists:reverse(Accum)) eof 或使用具有更好的附加操作或...的二进制文件)。另一种方法是不使用尾部递归函数,它不像以前看到的那样糟糕,根据神话:递归递归函数比递归函数快很多

file:read_file/1 is what you are looking for. Just for teaching purpose, Accum ++ [Line] is bad practice. Problem is that left argument of ++ is copied and right is used as is. In your code you will copy bigger and bigger part in each iteration. Solution is lists:reverse(Line,Accum) and than return lists:reverse(Accum) in your eof branch (Or [Line|Accum] and lists:append(lists:reverse(Accum)) at the eof or use binary which have better append operation or ...). Another way is not using tail recursive function which is not so bad as seems at first time according to Myth: Tail-recursive functions are MUCH faster than recursive functions.

所以你的 readlines / 1 函数应该看起来像

So your readlines/1 function should look like

readlines(FileName) ->
    {ok, Device} = file:open(FileName, [read]),
    try get_all_lines(Device)
      after file:close(Device)
    end.

get_all_lines(Device) ->
    case io:get_line(Device, "") of
        eof  -> [];
        Line -> Line ++ get_all_lines(Device)
    end.

这篇关于如何读取文件的内容在Erlang?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆