Chapter 11

I/O

On this page

Picat has an io module for reading input from files and writing output to files. The io module is imported by default.

The io module contains functions and predicates that read from a file, write to a file, reposition the read/write pointer within a file, redirect input and output, and create temporary files and pipes.

The io module uses file descriptors to read input from files, and to write output to files. A file descriptor is a structure that encodes file descriptor data, including an index in a file descriptor table that stores information about opened files. The following example reads data from one file, and writes the data into another file.

Example

rw =>
     Reader = open("input_file.txt"),
     Writer = open("output_file.txt", write),
     L = read_line(Reader),
     while (L != end_of_file)
            println(Writer, L),
            flush(Writer),
            L := read_line(Reader)
     end,
     close(Reader),
     close(Writer).

11.1 Opening a File

There are two functions for opening a file. Both of them are used in the previous example.

11.2 Reading from a File

The io module has at least one function for reading data into each primitive data type. It also has functions for reading characters, tokens, strings, and bytes. Recall that strings are stored as lists of single-character atoms.

The read functions in the io module take a file descriptor as the first parameter. This file descriptor is the same descriptor that the open function returns. The parameter can be omitted if it is the standard input file stdin. Unless specified otherwise explicitly, these functions throw an exception if FD is at the end of the file or the next token at FD is not of an expected type.

The bulk-read functions, including read_byte(FD, N), read_char(FD, N), and read_char_code(FD, N), may read fewer than N values. One case occurs when the end of the file is encountered. Another case occurs when reading from a pipe. If a pipe is empty, then the read functions wait until data is written to the pipe. As soon as the pipe has data, the read functions read the data. If a pipe has fewer than N values when a read occurs, then these three functions will return a list that contains all of the values that are currently in the pipe, without waiting for more values. In order to determine the actual number of elements that were read, after the functions return, use length(List) to check the length of the list that was returned.

The io module also has functions that peek at the next value in the file without changing the current file location. This means that the next read or peek function will return the same value, unless the read/write pointer is repositioned or the file is modified.

11.2.1 End of File

The end of a file is detected through the return of the end_of_file atom if the read function is read_line or read_char, the return of the value -1 if the read function is read_byte, or an exception if the read function is read_int. Instead of checking the returned value or exception, the at_end_of_stream predicate can be used to monitor a file descriptor for the end of a file.

Example

rw =>
     Reader = open("file1.txt"),
     Writer = open("file2.txt", write),
     while (not at_end_of_stream(Reader))
            L := read_line(Reader),
            println(Writer, L),
            flush(Writer)
     end,
     close(Reader),
     close(Writer).

The advantage of using the at_end_of_stream predicate instead of using the
end_of_file atom is that at_end_of_stream immediately indicates that the end of the file was reached, even if the last read function read values into a list. In the first example in this chapter, which used the end_of_file atom, an extra call to read_line was needed before the end of the file was detected. In the above example, which used at_end_of_stream, read_line was only called if there was data remaining to be read.

11.3 Writing to a File

The write and print predicates take a file descriptor as the first parameter. The file descriptor is the same descriptor that the open function returns. If the file descriptor is stdout, then the parameter can be omitted.

Note that these predicates write both primitive values and compound values.

The writef predicate includes a parameter that specifies the string that is to be formatted. The Format parameter is a string that contains format characters. Format characters take the form %[flags][width][.precision]specifier. Only the percent sign and the specifier are mandatory. Flags can be used for justification and padding. The width is the minimum number of characters that are to be printed. The precision is the number of characters that are to be printed after the number’s radix point. Note that the width includes all characters, including the radix point and the characters that follow it. The specifier indicates the type of data that is to be written. A specifier can be one of the C format specifiers %%, %c, 1 %d, %e, %E, %f, %g, %G, %i, %o, %s, %u, %x, and %X. In addition, Picat uses the specifier %n for newlines, and uses %w for terms. For details, see Appendix C.4.

Example

formatted_print =>
    FD = open("birthday.txt", write),
    Format1 = "Hello, %s.  Happy birthday!  ",
    Format2 =  "You are %d years old today.  ", 
    Format3 =  "That is %.2f%% older than you were last year.",
    writef(FD, Format1, "Bob"),
    writef(FD, Format2, 7),
    writef(FD, Format3, ((7.0 - 6.0) / 6.0) * 100),
    close(FD).

This writes Hello,Bob.Happy birthday!You are 7 years old today. That is 16.67% older than you were last year.

The io module also provides the print, printf, and println predicate families.

In addition to the above built-ins, the io module also provides the following:

The following example demonstrates the differences between the write and print predicates.

Example

Picat> write("abc")
[a,b,c]
Picat> write([a,b,c])
[a,b,c]
Picat> write('a@b')
'a@b'
Picat> writef("%w %s%n", [a,b,c], "abc")
[a,b,c] abc
Picat> print("abc")
abc
Picat> print([a,b,c])
abc
Picat> print('a@b')
a@b
Picat> printf("%w %s%n", [a,b,c], "abc")
abc abc

11.4 Flushing and Closing a File

The io module has one predicate to flush a file stream, and one predicate to close a file stream.

11.5 Standard File Descriptors

The atoms stdin, stdout, and stderr represent the file descriptors for standard input, standard output, and standard error. These atoms allow the program to use the input and output functions of the io module to read from and to write to the three standard streams.

1The specifier %ccan only be used to print ASCII characters. Use the specifier %wto print UTF-8 characters.