Problems with writing to file

Viewed 55

I have some prolog codes, I print processes on terminal. Also I write to file, what I print on terminal. I put write to file functs, near every write funct. But they are not same. Writing file is not working well.

printrow([]) :- write('  '),
    open('output.txt',append,OS), write(OS,'  '), close(OS).
    % I try to put same process for file
printrow([X|Xs]) :- printrepl(X,Y), write(' '), write(Y),               
    printrow(Xs), open('output.txt', append,OS),
    write(OS,' '), write(OS,Y), close(OS).

printrepl(' ',' ') :- !.
printrepl(x,'X').

printrows([]) :- nl.
printrows([N|Ns]) :- write(N), write(' '),
    open('output.txt', append,OS), write(OS,N), write(OS,' '),  
    printrows(Ns), write(OS,' \n'), close(OS).
   
% I can't find alternative for writef('%2r w',[X]) below, 
% for writing file, I think there is bug

writek(K,List) :- nth1(K,List,X), !, writef('%2r w',[X]),
    open('output.txt',append,OS), write(OS,' '), write(OS,X), close(OS).
writek(_,_) :- write('  '),
    open('output.txt',append,OS),write(OS,'  '), close(OS).

Can you give me advice for writing same outputs with terminal?

1 Answers

Here is a rewrite for writek and printrows. This could be of use.

% ---
% Printing rows (as "~w", equal to write/1) to stream Stream
% --- 

printrows([],Stream) :-
   format(Stream,"~n",[]).

printrows([N|Ns],Stream) :-
   format(Stream,"~w ~n",[N]),
   printrows(Ns,Stream).
   
% ---
% Printing/Appending Rows to the file named by Filename
% ---

printrows_to_file(Filename,Rows) :-
   setup_call_cleanup(
      open(Filename, append, Stream), % NB append
      printrows(Rows,Stream),
      close(Stream)).

% ---
% Printing Rows to stdout
% ---
      
printrows_to_stdout(Rows) :-
   printrows(Rows,user_output).
   
% ---
% Write "w", indented by 1-based value of List[K]
% ---

writek(K,List,Stream) :-
   nth1(K,List,Element),
   !,
   forall(between(1,Element,_),format(Stream," ",[])), % Indent
   format(Stream,"w~n",[]).

writek_to_file(Filename,K,List) :-
   setup_call_cleanup(
      open(Filename, append, Stream), % NB append
      writek(K,List,Stream),
      close(Stream)).

writek_to_stdout(K,List) :-
      writek(K,List,user_output).

For example:

?- printrows_to_stdout([1,2,3]). 
1 
2 
3 

true.

?- writek_to_stdout(1,[4,5,6]).
    w
true.

Similarly for

?- printrows_to_file('filename.txt',[1,2,3]).
?- writek_to_file('filename.txt',1,[4,5,6]).
Related