qutron
qutron

Reputation: 1760

How to save term to file in Prolog?

How can I save necessary terms to file? For example,

save_to_file(File) :-
    tell(File),
    listing,         
    told.   

saves all user terms to file File. But how can I save only necessary terms to file?

Upvotes: 2

Views: 2033

Answers (1)

false
false

Reputation: 10102

Your definition of safe_to_file/1 is safer using open/3 and close/1. Otherwise, interrupts or errors happening during listing/0 would leave the stream open, permitting other parts to write to the same file accidentally. So,

save_to_file(File) :-
   open(File,write,Stream),
   with_output_to(Stream, listing),
   close(Stream).

is safer. Now, only listing can write to that file. with_output_to/2 is specific to SWI, YAP.

To come back to your question, in most situations, portray_clause(Stream, Term) will be what you actually want.

Upvotes: 3

Related Questions