I/O & Files
20.1 io:format directives
pretty print (with depth limit) standard term output string / Unicode string ~b / ~B / ~.16B integer in base ~f / ~e / ~g
io:format("Hello ~s, you are ~p years old~n", ["Ann", 30]).
io:format("~w ~p~n", [[1, 2], "text"]). % ~w raw, ~p pretty
io:format("~10.2f|~-10s|~5..0B~n", [3.14159, "left", 42]).
io:format("~.16B ~e ~c ~ts~n", [255, 1.0e3, $a, <<"é"/utf8>>]).Str = io_lib:format("~p", [Term]), % returns chars (iolist)
lists:flatten(Str),
Bin = iolist_to_binary(io_lib:format("~p", [Term])).20.2 Reading input
Name = io:get_line("Name: "), % includes "\n"
{ok, [N]} = io:fread("Number: ", "~d"),
io:read("Term: "). % read an Erlang term20.3 Files
{ok, Bin} = file:read_file("data.txt"),
ok = file:write_file("out.txt", <<"hello\n">>),
ok = file:write_file("log.txt", "more\n", [append]),
{ok, Terms} = file:consult("config.terms"), % read Erlang terms from file
{ok, Fd} = file:open("data.txt", [read, binary]),
read_lines(Fd) ->
case file:read_line(Fd) of
{ok, Line} -> [Line | read_lines(Fd)];
eof -> file:close(Fd), []
end.
file:list_dir("."), file:make_dir("d"), file:delete("f"), file:rename("a", "b"),
file:copy("a", "b"), file:read_file_info("f"), file:get_cwd(),
filelib:is_file("f"), filelib:is_dir("d"), filelib:ensure_dir("a/b/c"),
filelib:ensure_path("a/b"), % OTP 25+
filelib:wildcard("src/**/*.erl"), filelib:file_size("f"),
filename:join(["a", "b", "c.erl"]), filename:basename("/x/y.erl"),
filename:dirname("/x/y.erl"), filename:extension("y.erl"), filename:rootname("y.erl"),
filename:absname("x").20.4 OS interaction
os:cmd("ls -l"),
os:getenv("HOME"), os:getenv("X", "default"), os:putenv("X", "1"),
os:type(), os:timestamp(), os:system_time(millisecond),
init:get_plain_arguments(),
halt(0).