2011-11-12 103 views
1

我有一個文本文件,我想讀取它並在屏幕上打印出來並寫入一個新的輸出文件。所以我做了什麼至今如何讀取文本文件並將其打印到Prolog中的文件中?

main :- 
    open('text.txt', read, ID), % open a stream 
    repeat,    % try again forever 
    read(ID, X),  % read from the stream 
    write(X), nl,  % write to current output stream 
    X == end_of_file, % fail (backtrack) if not end of 
    !, 
    close(ID). 

但我只收到一條錯誤消息一樣,

ERROR: text.txt:1:0: Syntax error: Operator expected 

我該怎麼辦?

回答

2

read/2讀取有效的序言文本。該消息表明,在text.txt的第1行中,您有一些無效的Prolog文本。也許兩個詞用空格分隔。

如果你想閱讀普通文本,你可以使用get_char/2來做到非常低級,或者你可能想用語法來做到更高級別。 SWI-Prolog有library(pio)

這裏是Prolog程序員的等價物grep -q

?- phrase_from_file((...,"root",...),'/etc/passwd'). 
true ; 
true ; 
true ; 
false. 

其實這就是grep -c

你需要下載以下定義它:

... --> [] | [_], ... . 
0
is_eof(FlHndl, CharCode, CurrentLine, FileAkku, FileContent) :- 
     CharCode == -1, 
     append(FileAkku, [CurrentLine], FileContent), 
     close(FlHndl), !. 

is_newline(FlHndl, CharCode, CurrentLine, FileAkku, FileContent) :- 
     CharCode == 10, 
     append(FileAkku, [CurrentLine], NextFileAkku), 
     read_loop(FlHndl, '', NextFileAkku, FileContent). 

append_char(FlHndl, CharCode, CurrentLine, FileAkku, FileContent) :- 
     char_code(Char, CharCode), 
     atom_concat(CurrentLine, Char, NextCurrentLine), 
     read_loop(FlHndl, NextCurrentLine, FileAkku, FileContent). 

read_file(FileName, FileContent) :- 
     open(FileName, read, FlHndl), 
     read_loop(FlHndl, '', [], FileContent), !. 

read_loop(FlHndl, CurrentLine, FileAkku, FileContent) :- 
     get_code(FlHndl, CharCode), 
     (is_eof(FlHndl, CharCode, CurrentLine, FileAkku, FileContent) 
     ; is_newline(FlHndl, CharCode, CurrentLine, FileAkku, FileContent) 
     ; append_char(FlHndl, CharCode, CurrentLine, FileAkku, FileContent)). 

main(InputFile, OutputFile) :- 
    open(OutputFile, write, OS), 
    ( read_file(InputFile,InputLines), 
     member(Line, InputLines), 
     write(Line), nl, 
     write(OS,Line),nl(OS), 
     false 
     ; 
     close(OS) 
    ). 

所以,你可以使用它像main('text.txt', 'output.txt').

1

如果你想要一個可重用的代碼片段:

%% file_atoms(File, Atom) is nondet. 
% 
% read each line as atom on backtrack 
% 
file_atoms(File, Atom) :- 
    open(File, read, Stream), 
    repeat, 
    read_line_to_codes(Stream, Codes), 
    ( Codes \= end_of_file 
    -> atom_codes(Atom, Codes) 
    ; close(Stream), !, fail 
    ). 

這調用一個SWI-Prolog內置的read_line_to_codes。

相關問題