12.2 Writing to Files
Many applications require that output be written to a file rather than to the screen. In this section we will explain how to do this in Prolog.
In order to write to a file we have to create one (or open an existing one) and associate a stream with it. You can think of streams as connections to files. In Prolog, streams are blessed with names in a rather user-unfriendly format, such as ’\$stream’(183368) . Luckily, you never have to bother about the exact names of streams — although Prolog assigns these names internally, you can use Prolog’s unification to match the name to a variable and make use of the variable rather than the name of the stream itself.
Say you want to print the string ’Hogwarts’ to the file hogwarts.txt . This is done as follows:
... open('hogwarts.txt',write,Stream), write(Stream,'Hogwarts'), nl(Stream), close(Stream), ...
What’s happening here? Well, first the built-in predicate open/3 is used to create the file hogwarts.txt . The second argument of open/3 indicates that we want to open a new file (overwriting any existing file with the same name). The third argument of open/3 returns the name of the stream. Secondly, we write ’Hogwarts’ on the stream and issue a newline command as well. After this we are ready, and close the stream, using the built-in close/1 .
And that’s more or less all there is to it. As promised, we were not interested in the name of the stream — we used the variable Stream to pass it around. Also note that the write/2 predicate we used here is basically a more general form of the write/1 predicates we used in Chapter 9 for writing to the screen.
What if you don’t want to overwrite an existing file but append to an existing one? This is done by choosing a different mode when opening the file: instead of write , use append as value for the second argument of open/3 . If a file of the given name doesn’t exist, it will be created.