Writing Files in Erlang

Here’s the translation of the Go code to Erlang, with explanations in Markdown format suitable for Hugo:

Writing files in Erlang follows similar patterns to the ones we saw earlier for reading.

-module(writing_files).
-export([main/0]).

main() ->
    % To start, here's how to dump a string (or just bytes) into a file.
    D1 = "hello\nerlang\n",
    ok = file:write_file("/tmp/dat1", D1),

    % For more granular writes, open a file for writing.
    {ok, F} = file:open("/tmp/dat2", [write]),

    % It's idiomatic to ensure the file is closed when we're done.
    % In Erlang, we can use the 'try ... after' construct for this.
    try
        % You can write binaries as you'd expect.
        D2 = <<"some\n">>,
        ok = file:write(F, D2),
        io:format("wrote ~p bytes~n", [byte_size(D2)]),

        % A write_string function is also available.
        ok = file:write(F, "writes\n"),
        io:format("wrote ~p bytes~n", [length("writes\n")]),

        % Erlang automatically flushes writes to stable storage,
        % so there's no need for an explicit sync operation.

        % The 'io' module provides buffered writers.
        ok = io:format(F, "buffered~n", []),
        io:format("wrote ~p bytes~n", [length("buffered\n")])

        % Erlang automatically flushes the buffer when the file is closed,
        % so there's no need for an explicit flush operation.
    after
        file:close(F)
    end.

Try running the file-writing code:

$ erl -noshell -s writing_files main -s init stop
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files:

$ cat /tmp/dat1
hello
erlang

$ cat /tmp/dat2
some
writes
buffered

Next, we’ll look at applying some of the file I/O ideas we’ve just seen to the standard input and output streams.