Search code examples
databaseloggingprologswi-prologprolog-toplevel

Write queries results into a file in prolog


Here is my prolog database code.

:-
    dynamic myTable/2.

init :-
    removeAll,
    asserta(myTable('avalue', 'another value')),
    asserta(myTable('avalue1', 'another value 1')),
    asserta(myTable('avalue2', 'another value 2')),
    asserta(myTable('avalue3', 'another value 3')),
    asserta(myTable('avalue4', 'another value 4')).

read(Col1, Col2) :-
    myTable(Col1, Col2).

saveQueries(FileName) :-
    tell(FileName).

stopSavingQueries :-
    told.

I want to start saving prolog output into a file. Make some queries to the dynamic database, which should be saved into the file, and then stop saving the queries. It would look something like this

?- init.
true.

?- saveQueries('queries.txt').
true.

?- read(Col1, Col2).
...
?- stopSavingQueries.
true.

When I run this code file queries.txt is created. When I run read(Col1, Col2). I see the output in the console and the file queries.txt remains empty.


Solution

  • After googling for a while I found this solution.

    saveQueries(FileName) :-
        protocol(FileName).
    
    stopQueriesSaving :-
        noprotocol.
    

    Then I can do this

    ?- saveQueries('queries.txt').
    true.
    
    /* execute some queries here */
    
    ?- stopQueriesSaving.
    true.
    

    After I execute those commands I have a file queries.txt which contains all the queries and their results.