读取erlang

时间:2018-06-23 15:38:18

标签: functional-programming erlang

我按照此方法读取文件-how to read the contents of a file In Erlang?

提到的答案很好。但是,我的文件内容如下:

{0, {data, node, 0}}
{1, {someData, node, 1}}

每行都会有此数据。因此,在读取文件时,我想过滤应读取的行数 像这样的东西:

read(Node, FirstIndex, LastIndex, F, Acc)

在这里,F是fold函数,它接受一个日志条目和当前累加器,并返回新的累加器值。

如何将解决方案与所需的功能结合在一起?

1 个答案:

答案 0 :(得分:0)

-module(my).
-compile(export_all).

get_section(Start, End, Fname) when Start>0, End>=Start ->
    {ok, Io} = file:open(Fname, read),
    ok = advance_file_pointer(Start, Io),
    Lines = getNLines(End-Start+1, Io),
    file:close(Io),
    Lines.

advance_file_pointer(1, _Io) ->
    ok;
advance_file_pointer(Start, Io) ->
    {ok, _Line} = file:read_line(Io),
    advance_file_pointer(Start-1, Io).

getNLines(N, Io) ->
    getNLines(N, Io, []).

getNLines(0, _Io, Acc) ->
    lists:reverse(Acc);
getNLines(N, Io, Acc) ->
    {ok, Line} = file:read_line(Io),
    getNLines(N-1, Io, [Line|Acc]).

在外壳中:

~/erlang_programs$ cat data.txt
{1, {data, node, 1}}
{2, {someData, node, 2}}
{3, {otherData, node, 3}}

~/erlang_programs$ erl
Erlang/OTP 20 [erts-9.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V9.2  (abort with ^G)
1> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}

2> my:get_section(1, 1, "data.txt").
["{1, {data, node, 1}}\n"]

3> my:get_section(1, 2, "data.txt").
["{1, {data, node, 1}}\n","{2, {someData, node, 2}}\n"]

4> my:get_section(1, 3, "data.txt").
["{1, {data, node, 1}}\n","{2, {someData, node, 2}}\n",
 "{3, {otherData, node, 3}}\n"]

5> my:get_section(2, 3, "data.txt").
["{2, {someData, node, 2}}\n","{3, {otherData, node, 3}}\n"]
6> my:get_section(2, 2, "data.txt").
["{2, {someData, node, 2}}\n"]

7> my:get_section(0, 2, "data.txt").
** exception error: no function clause matching my:get_section(0,2,"data.txt") (my.erl, line 4)

8> my:get_section(1, 4, "data.txt").
** exception error: no match of right hand side value eof
     in function  my:getNLines/3 (my.erl, line 20)
     in call from my:get_section/3 (my.erl, line 7)

9> 

您可以在getNLines/3的第二子句中应用折叠功能。