我想通过使用erlang逐行读取文件来检查外部文件中是否存在特定的字符串。如果特定的字符串不存在,我希望在文件后附加该字符串。到目前为止,我已经设法打开文件并逐行读取文件内容。但我不知道如何进行其余的工作。我是erlang的新手,因此非常感谢您对此问题的任何帮助。
到目前为止我尝试过的:
-module(helloworld).
-export([readlines/1,get_all_lines/1,start/0]).
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.
start() ->
readlines("D:\\documents\\file.txt"),
Txt=file:read_file("D:\\documents\\file.txt"),
io:fwrite("~p~n", [Txt]).
我得到的结果:
helloworld:start()。{ok,<>}好
我正在使用的示例文件:文件名:“ file.txt”
文件内容:你好嗨
如果需要尝试在文件中查找特定文本,可以尝试使用re:run/2功能。这是示例,您可以尝试在文件中查找specific string
,如果找不到该字符串-字符串将被记录在log.txt
文件中:
-module(helloworld).
-export([start/0]).
-define(LOG_FILE, "log.txt").
start() -> read_data("file.txt").
read_data(FileName) ->
case file:read_file(FileName) of
{error, enoent} -> io:format("File ~p not found~n", [FileName]);
{ok, Data} -> read_all_lines(Data)
end.
read_all_lines(Data) ->
Word = <<"specific string">>,
case re:run(Data, Word) of
nomatch -> write_log(Word);
_ -> ok
end.
write_log(Word) ->
case file:read_file(?LOG_FILE) of
{ok, Data} when Data =/= <<>>-> file:write_file(?LOG_FILE, <<Data/binary, "\n", Word/binary>>);
_ -> file:write_file(?LOG_FILE, Word)
end.