使用erlang在文本文件的特定行的末尾写一个单词

时间:2013-10-13 08:54:56

标签: file erlang

如何在Erlang的文件中指定行的末尾写一个单词,比如说

第1行:“他是约翰”

write_word("poem.txt",1," doe.").

第1行:“他是约翰·多伊。”

这就是我能做的所有事情:

 write_word(Filename, LineNumber, Word) ->
        {ok, Data} = file:open(FileName, [read, write]),
        % write the word at end of line with the specified line number

1 个答案:

答案 0 :(得分:0)

下面提供了一种伪代码(未经测试的代码)。此外,您还必须将内容写入新文件

openFile(FileName, Mode, DesiredLine) ->
    {ok, FD} = file:open(FileName, Mode),
    for_each_line(FD, 0, DesiredLine).

for_each_line(FD, LineNo, DesiredLine) ->
    case io:get_line(FD, "") of
        eof  -> 
             file:close(FD);
        Line -> 
             case LineNo =:= DesiredLine of
             false ->
                 %% Write into a new file
                 NewLine = Line,
                 for_each_line(FD, LineNo + 1);
             true ->
                  %% do your stuff
                  NewLine = Line ++ "Word",
                  %% write into your file
              end    

    end.