September 2013
Intermediate to advanced
548 pages
12h 25m
English
Writing to a file involves pretty much the same operations as reading a file. Let’s look at them.
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}]} ... |
Read now
Unlock full access