Write Term to File

zxq9 zxq9@REDACTED
Wed Jan 27 04:39:52 CET 2021

Hi, Oliver.

The lack of an inverse function for file:consult/1 comes up from time to 
time. I've written about it here:

TL;DR: You want a function like this:

   -spec write_terms(Filename, Terms) -> ok
       when Filename :: file:filename(),
            Terms    :: [term()].
   %% @private
   %% Provides functionality roughly inverse to file:consult/1.

   write_terms(Filename, List) ->
       Format = fun(Term) -> io_lib:format("~tp.~n", [Term]) end,
       Text = unicode:characters_to_binary(lists:map(Format, List)),
       file:write_file(Filename, Text).

For the example I put this in a module called "writer".
The IMPORTANT thing to note is the flag passed to Erlang on startup:
`erl +pc unicode`

   ceverett@REDACTED:~/Code/erlang$ erl +pc unicode
   Erlang/OTP 23 [erts-11.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] 
[async-threads:1] [hipe]

   Eshell V11.1  (abort with ^G)
   1> c(writer).
   2> writer:write_terms("blah.txt", ["Some English", "何かの日本語"]).
   3> q().
   ceverett@REDACTED:~/Code/erlang$ cat blah.txt
   "Some English".

Little details like this make the unicode world go round. I'm not quite 
sure why Erlang doesn't default to unicode, but whatever.

Keep in mind that the function above expects to receive a list. That is, 
you must called write_terms(Path, ["漢"]), not write_terms(Path, "漢").


On 2021/01/27 7:52, Oliver Bollmann wrote:
> How can i write term to file, for later using in file:consult?
> I do:
> R = io_lib:format("~tp.",[{"cn","漢"}]),
> file:write_file(FileName,R)
> But this gives:
> {"cn",[28450]}.
> I need:
> {"cn","漢"}.
> Any hints?

More information about the erlang-questions mailing list