【问题标题】:read a file of specific content in erlang在erlang中读取特定内容的文件
【发布时间】:2018-12-02 19:12:33
【问题描述】:

我按照这个方法读取文件-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 是折叠函数,它接受单个日志条目和当前累加器并返回新的累加器值。

我怎样才能将解决方案与我需要的这个功能结合起来??

【问题讨论】:

    标签: functional-programming erlang


    【解决方案1】:
    -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 的第二个子句中应用您的折叠功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      相关资源
      最近更新 更多