Erlang Language File I/O Writing to a file


Write one line at a time

Open a file with write mode and use io:format/2:

1> {ok, S} = file:open("fruit_count.txt", [write]).
2> io:format(S, "~s~n", ["Mango 5"]).
3> io:format(S, "~s~n", ["Olive 12"]).
4> io:format(S, "~s~n", ["Watermelon 3"]).

The result will be a file named fruit_count.txt with the following contents:

Mango 5
Olive 12
Watermelon 3

Note that opening a file in write mode will created it, if not already existent in the file system.

Note also that using the write option with file:open/2 will truncate the file (even if you don't write anything into it). To prevent this, open the file in [read,write] or [append] mode.

Write the entire file at once

file:write_file(Filename, IO) is the simplest function for writing a file at once. If the file already exists, it will overwritten, otherwise it will be created.

1> file:write_file("fruit_count.txt", ["Mango 5\nOlive 12\nWatermelon 3\n"
2> file:read_file("fruit_count.txt").
{ok,<<"Mango 5\nOlive 12\nWatermelon 3\n">>}

Write with random access

For random access writing, file:pwrite(IoDevice, Location, Bytes) is used. If you want to replace some string in the file, this method is useful.

Let's assume you want to change "Olive 12" to "Apple 15" in the file created above.

1> {ok, S} = file:open("fruit_count.txt", [read, write]).
2> file:pwrite(S, 8, ["Apple 15\n"]).
3> file:read_file("fruit_count.txt").
{ok,<<"Mango 5\nApple 15\nWatermelon 3">>}
4> file:close(S).