跳轉到內容

Prolog/輸入輸出

來自華夏公益教科書,開放的書籍,為一個開放的世界

檔名約定

[編輯 | 編輯原始碼]

檔名必須放在單引號之間,這樣它們才能成為原子。("foo.txt" 不起作用,因為它是一個字元列表而不是一個原子。)在 Windows 系統中,您可以將路徑寫為 'C:/foo.txt' 或 'C:\\foo.txt'。

以愛丁堡風格讀取檔案

[編輯 | 編輯原始碼]

您可以使用 see/1 開啟檔案,並使用 seen/0 關閉。以下程式讀取一個檔案,並將其列印到標準輸出。


process(X):-
        X = 'c:/readtest.txt',
        see(X),
        repeat,
        get_char(T),print(T),T=end_of_file,!,seen.

您可以同時開啟多個檔案:如果您使用 see(file1),然後 see(file2),您將同時擁有 2 個開啟的檔案,如果您現在呼叫 get_char,它將從 file2 讀取。如果您再次呼叫 see(file1),file1 將再次啟用。您可以按任何順序關閉這些檔案。

read 謂詞用於解析 Prolog 項。(它也可以處理 DCG 語法。)您可能需要它用於自我修改程式,或用於轉換 Prolog 程式碼的程式。

以 ISO 風格讀取檔案

[編輯 | 編輯原始碼]

在遵循 ISO 標準時,來自檔案和網路的資料以相同的方式處理:作為資料流。

  • 開啟一個檔案以供讀取:open(Filename, read, Streamhandler)
  • 開啟一個檔案以供寫入:open(Filename, write, Streamhandler)


process(File) :-
        open(File, read, In),
        get_char(In, Char1),
        process_stream(Char1, In),
        close(In).

process_stream(end_of_file, _) :- !.
process_stream(Char, In) :-
        print(Char),
        get_char(In, Char2),
        process_stream(Char2, In).
華夏公益教科書