Erlang Central

Category:FileRecipes

Revision as of 02:49, 4 September 2006 by Bfulgham (Talk | contribs)

Introduction

This chapter deals with file access; that is, opening files, passing files as arguments to procedures that work with them, and so on.

File access and manipulation in Erlang is done by means of IoDevices (terms representing files, such as Standard Input and Output, or disk files). It's required that IoDevice terms associated with physical files be closed when they're no longer in use. IoDevices can be opened using the normal file permissions from standard POSIX file systems (read, write, append, raw).

All I/O procedures take as an optional parameter an IoDevice, and if not specified they will use the standard input (or standard output) device.

1> {ok, FileId} = file:open("hello.txt", [read write]).
{ok, <0.187.0>}
2> io:fwrite(FileId, "~s~n", ["Hello there"]).
ok
3> file:close(FDev2).
ok

Random file access can be achieved by using the procedure position. This can be used either to obtain the current read/write position of a device, and to change it.

4> {ok,FDev2} = file:open("hello.txt", [read]).
{ok,<0.31.0>}
5> file:position(FDev2, 5).  
{ok,5}
6> Str = file:read(FDev2, 16).
{ok," there\n"}