Fork me on GitHub

Erlang io:format to string

2009-03-29

This is quite a FAQ

How do you get the result from io:format into a string.

So here goes.

There is an io_lib:format which returns the formatted result instead of printing it. Notice io_lib as module name instead of io. The result is not necessarily a flat list. No. The result might look like the following.

1> io_lib:format("foo ~p bar~n", [42]).
[102,111,111,32,"42",32,98,97,114,"\n"]
2> erlang:iolist_to_binary(v(1)).
<<"foo 42 bar\n">>
3> lists:flatten(v(1)).
"foo 42 bar\n"

But as you see, there are ways to flatten the result. It is not done per automation since all data sent to ports are flattened there anyway. Ports include files, other processes, sockets, etc. The concept is called “iolist”. If you want the byte-count of an iolist, then use erlang:iolist_size.

Finally I would like to point out a little useful function called lists:concat (which is nothing like lists:append).

4> lists:concat([foo," ", 42, " ", bar, "\n"]).
"foo 42 bar\n"