How read a file and write another file in prolog

徘徊边缘 提交于 2020-01-11 13:42:28

问题


I would like to read a file, modify lines and write the results to another file.


readtofile :-
    open('inputfile.txt', read, Str),
    read_file(Str,Lines),
    close(Str).


read_file(Stream) :-
    at_end_of_stream(Stream).

read_file(Stream) :-
    \+ at_end_of_stream(Stream),
    read(Stream),
    modify(Stream,Stream2),
    write_file(Stream2),    
    read_file(Stream).      


write_file('outputfile.txt', Phrase) :-
    open('outputfile.txt', write, Stream),
    writeln(Stream, Phrase),
    close(Stream).  


回答1:


I would write something like

tranform_file :-
    open('inputfile.txt', read, I),
    open('outputfile.txt', write, O),
    transform_lines(I, O),
    close(O),
    close(I).

transform_lines(I, O) :-
   read_line_to_codes(I, L),
   (  L == end_of_file
   -> true
   ;  transform_line(L, T),
      format(O, '~s~n', [T]),
      transform_lines(I, O)
   ).

(note: untested)



来源:https://stackoverflow.com/questions/16855982/how-read-a-file-and-write-another-file-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!