简体   繁体   中英

Write a word at the end of a specific line in a text file using erlang

How can I write a word at the end of a specified line in a file in Erlang, let's say

Line 1: "He is john"

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

Line 1: "He is john doe."

This is all I can manage to do:

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

Below provided is kind of a pseudo code(untested one). Also you will have to write the contents to a new file

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM