3

I want to check if a specific string is present in a external file,by reading the file line by line using erlang. If the specific string is not present ,I wish to append the file with the string. So far I have managed to open the file and read the file contents line by line. but i have no idea how to proceed with the rest. I am new to erlang so any help on this question will be highly appreciated.

What I have tried so far:

-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]).



What I got as the result:

helloworld:start(). {ok,<<"hello\r\nhi">>} ok

The sample file that I am using : file name:"file.txt"

file contents: hello hi

Community
  • 1
  • 1

1 Answers1

2

If you need try find specific text in file you can try use re:run/2 function. Here is example how you can try find specific string in file and if you don't find this string - the string will be will be recorded in log.txt file:

-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} ->
      find_text(Data)
  end.

find_text(Data) ->
  Text = <<"specific string">>,
  case re:run(Data, Text) of
    nomatch ->
      write_log(Text);
    _ ->
      ok
  end.

write_log(Text) ->
  case file:read_file(?LOG_FILE) of
    {ok, Data} when Data =/= <<>> ->
      file:write_file(?LOG_FILE, <<Data/binary, "\n", Text/binary>>);
    _ ->
      file:write_file(?LOG_FILE, Text)
  end.
vkatsuba
  • 1,411
  • 1
  • 7
  • 19
  • 1
    Thank you so much for your help!! The code snippet was really useful. – Vinuri Mithara Jan 30 '20 at 11:11
  • Can we manage to define a macro inside a function? Something like the code given below? – Vinuri Mithara Jan 31 '20 at 06:43
  • module(helloworld). -export([createVariables/2,start/0]). createVariables(ProjectName,UserName)-> -define(PROJECT_NAME,ProjectName), -define(USER_NAME,UserName). start() -> createVariables("dev_test_007", "abcd"), ``` – Vinuri Mithara Jan 31 '20 at 06:45
  • You can define macros in any place of module, but good code style is an or create macros in header file, or in head of module. – vkatsuba Jan 31 '20 at 09:11