Ways to Write a File
Writing to a file involves pretty much the same operations as reading a file. Let’s look at them.
Writing a List of Terms to a File
Suppose we want to create a file that we can read with
file:consult
. The standard libraries don’t actually
contain a function for this, so we’ll write our own. Let’s
call this function unconsult
.
lib_misc.erl | |
| unconsult(File, L) -> |
| {ok, S} = file:open(File, write), |
| lists:foreach(fun(X) -> io:format(S, "~p.~n",[X]) end, L), |
| file:close(S). |
We can run this in the shell to create a file called test1.dat.
| 1> lib_misc:unconsult("test1.dat", |
| [{cats,["zorrow","daisy"]}, |
| {weather,snowing}]). |
| ok |
Let’s check that it’s OK.
| 2> file:consult("test1.dat"). |
| {ok,[{cats,["zorrow","daisy"]},{weather,snowing}]} ... |
Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.