[erlang-questions] Erlang Basics: Reading File Content
Atul Goyal
atulindore2@REDACTED
Tue Dec 17 01:59:36 CET 2013
File IO is one thing I really love in Erlang.
Especially with sockets , we can use :
file:sendfile/2 (http://www.erlang.org/doc/man/file.html#sendfile-2)
for example :
somefunction()->
....
....
{ok,Sock}=gen_tcp:connect( Ip , Port , []) ,
....
....
{ok,Bytes_sent} = file:sendfile(Filename , Sock)
....
....
Of course you can add some error checking code to it :).
>
> Message: 4
> Date: Mon, 16 Dec 2013 09:48:34 -0500
> From: Ari King <ari.brandeis.king@REDACTED>
> To: erlang-questions@REDACTED
> Subject: [erlang-questions] Erlang Basics: Reading File Content
> Message-ID:
> <CAPcS2ahcV5=fk62ikS6kGGdMj+ZYGBLLrz12xiSkUduPO5cTjw@REDACTED>
> Content-Type: text/plain; charset="iso-8859-1"
>
> 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-0001.html>
More information about the erlang-questions
mailing list