[erlang-questions] Erlang Basics: Reading File Content

Bob Ippolito <>
Mon Dec 16 16:48:51 CET 2013


The last expression of a function is what that function returns. Are you
trying to stream the file to the socket a line at a time, or are you trying
to read the entire file and then write its contents to the socket en masse?
For the former, you would simply have get_data take two arguments, a Device
and Socket. When you read anything but eof from the device you would write
the Data to Socket and then tail-recurse (`get_data(Device, Socket)` not a
list). The eof case would simply return ok. For the latter case you could
use your implementation of get_data as-is, and write its result to Socket.

Either way, there's not usually a need to use try/after to close a Port
(such as a file or socket) in exceptional situations. The Port is linked to
the process and will automatically be closed when the process dies. You
should of course still close it in normal situations so that the file
descriptor is reclaimed at the intended moment (perhaps immediately on eof).

-bob


On Mon, Dec 16, 2013 at 9:48 AM, Ari King <>wrote:

> 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
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20131216/0aa89471/attachment.html>


More information about the erlang-questions mailing list