Erlang Central


From ErlangCentral Wiki


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"]).
3> file:close(FileId).

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]).
5> file:position(FDev2, 5).  
6> Str = file:read(FDev2, 16).
{ok," there\n"}


This category has only the following subcategory.