Prolog/Input and Output

Filename conventionEdit

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 styleEdit

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:

        X = 'c:/readtest.txt',

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 styleEdit

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),

process_stream(end_of_file, _) :- !.
process_stream(Char, In) :-
        get_char(In, Char2),
        process_stream(Char2, In).