Erlang: How to pipe stdin input from a file to an erlang program and match eof?

南笙酒味 提交于 2019-12-04 11:48:23

This is one of the Erlang FAQs:

http://www.erlang.org/faq/how_do_i.html#id49435

Look here for the fastest line oriented IO for Erlang known to me. Note the usage of -noshell and -noinput command line parameters. Key part is

read() ->
   Port = open_port({fd, 0, 1}, [in, binary, {line, 256}]),
   read(Port, 0, [], []).

read(Port, Size, Seg, R) ->
  receive
    {Port, {data, {eol, <<$>:8, _/binary>> = Line}}} ->
      read(Port, Size + size(Line) + 1, [],
        [iolist_to_binary(lists:reverse(Seg, [])) | R]);
    {Port, {data, {eol, Line}}} ->
      read(Port, Size + size(Line) + 1, [Line | Seg], R);
    {'EXIT', Port, normal} ->
      {Size, [list_to_binary(lists:reverse(Seg, [])) | R]};
    Other ->
      io:format(">>>>>>> Wrong! ~p~n", [Other]),
      exit(bad_data)
  end.

EDIT: Note that the line oriented IO was fixed in R16B http://erlang.org/pipermail/erlang-questions/2013-February/072531.html so you need this trick no longer.

EDIT2: There is an answer using fixed file:read_line/1.

I am able to pipe input when using escript. Write the erlang program without module or export info, with main(_) function, i.e., in escript compatible way. Then we can pipe input using cat like

cat inp.txt | escript hr.erl

This works and program terminates when it encounters eof. But I still don't know why it's not working when using redirect operator <.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!