Prolog/Input and Output

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Filename convention[edit | edit source]

Filenames must be put between apostrophes, so they become atoms. ( "foo.txt" will not work, because it's a list of characters and not an atom.) In Windows systems you can write paths as 'C:/foo.txt' or 'C:\\foo.txt'.

Reading a file the Edinburgh style[edit | edit source]

You can open a file with see/1 and close with seen/0. The following program reads a file, and prints it to the standard output:


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

You can have multiple files open at the same time: If you use see(file1) and then see(file2), you will have 2 open files at the same time, and if you now call get_char, it will read from file2. If you call see(file1) again, file1 will be active again. You can close these files in any order you want.

The read predicate is for parsing prolog terms. (It can handle DCG grammars as well.) You might need it for self-modifying programs, or for programs which transforms prolog code.

Reading a file the ISO style[edit | edit source]

When following the ISO standard, data from files and from network are handled the same way: as data streams.

  • Open a file for reading: open(Filename, read, Streamhandler)
  • Open a file for writing: 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).