What is the opposite of write_canonical
to read it back in?
It seems there is no read_canonical
.
Ordinary read/1 will do what you want. write_canonical/1 outputs without operators (a+b
will output as +(a,b)
), so there’s nothing in the reader’s environment to change the meaning of terms that are being read in. (If write_canonical/1 were to output in infix/prefix/postfix form, then the same operator definitions would need to be set up to read in the terms correctly.)
BTW, there are also faster ways of reading and writing terms: fast_read/2, fast_write/2, fast_term_serialized/2 - but they’re specific to SWI-Prolog.
I’m able to use write_canonical
and write_term
and successful write a file. But when I try fast_write
writing the same file name where the file does not exist yet, I get “ERROR: NO permission to fast_write stream”. Do I need to create the stream differently in order to use fast_write
?
I figured it out. I needed to tell it the file was binary. In case someone searches for this in the future, here’s a short demo that works:
:- initialization
File = "demo.pb",
Data = foo(bar, baz),
Options = [type(binary)],
open(File, write, WStream, Options),
fast_write(WStream, Data),
close(WStream),
open(File, read, RStream, Options),
fast_read(RStream, NewData),
close(RStream),
format('NewData = ~w~n', NewData),
halt.
I use the open options [encoding(octet),type(binary)]
for both reading and writing with fast_write/2 etc. – perhaps the encoding(octet)
isn’t needed, but it doesn’t seem to hurt.
They are supposed to be the same. ISO defines type(binary)
. SWI-Prolog added the notion of encodings where it was practical to define an additional encoding for “not encoded”, e.g., “binary”. If you want to read/write a binary file, I’d use (only) type(binary)
.