[erlang-questions] Erlang Basics: Reading File Content

Ari King ari.brandeis.king@REDACTED
Mon Dec 16 15:48:34 CET 2013


I've just started with Erlang and to learn/practice I'm attempting to put
together a simple TCP server that reads data from a file and writes it to a
socket. So far I've put together some code to read the data (combination of
ascii, binary, control characters). But since (as I understand) Erlang
doesn't have a return mechanism, how do I read a line of data and return it
to be written to the socket? Right now, the code just recursively collects
the data.

    -module(mock_tcp).
    -export([start/1]).

    start([Ip, Port, Filename]) ->
      io:format("Server available at ~w on port ~w. Reading from ~w.", [Ip,
Port, Filename]),
      {ok, Device) = file:open(Filename, read),
      try get_data(Device)
        after file:close(Device)
      end.

    get_data(Device) ->
      case io:get_line(Device) of
        {ok, Data} -> [Data | get_data(Device)];
        eof -> []
      end.

Thanks.

Ari
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20131216/f89f2e87/attachment.htm>


More information about the erlang-questions mailing list