My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
TutorialFourFileIO  
Tutorial Part Four: File IO
Updated Feb 5, 2010 by noah.die...@gmail.com

Introduction

To open a file in Erlang, we use the 'file:open' method, which takes 2 parameters, the filename and the access type (read, write). The return value of the method is a tupple of either {ok, FileHandle} or {error, Why} (where error and ok are atoms}. We can then read data from the file in a number of ways, including 'read' to to get an Erlang Term from a file, 'consult' to read all erlang terms from a file, or 'get_line' to get the next line of text from a file. for example:

> {ok, S} = file:open("data1.dat", read).  %open the file for reading
{ok, <0.43.0> }			%S points to this PID so we can continue to access this file.
> io:get_line(S, '').	& get the next line of text from file handle S
{text from file}
>

To copy the entire contents of a file into a binary, you can use the 'read_file' method:

> file:read_file("data1.dat").
{..binary data...}
>

Sign in to add a comment
Powered by Google Project Hosting