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.
- open() = : The parameter is a file name that is represented as a string. This function opens the file with a default read mode.
- open(, ) = : The parameter is one of the three atoms: read, write, or append. The read atom is used for reading from a file; if the file does not exist, or the program tries to write to the file, then the program will throw an error. The write atom is used for reading from a file and writing to a file; if the file already exists, then the file will be overwritten. The append atom is similar to the write atom; however, if the file already exists, then data will be appended at the end of the pre-existing file.
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 is at the end of the file or the next token at is not of an expected type.
- read_atom() = : This function reads a single atom from .
- read_atom() = : This function is the same as read_atom(stdin).
- read_byte() = : This function reads a single byte from . It returns -1 if is at the end of the file.
- read_byte() = : This function is the same as read_byte(stdin).
- read_byte(, ) = : This function reads up to bytes from . It returns the list of bytes that were read.
- read_char() = : This function reads a single UTF-8 character from . It returns end_of_file if is at the end of the file.
- read_char() = : This function is the same as read_char(stdin).
- read_char(, ) = : This function reads up to UTF-8 characters from . It returns a string that contains the characters that were read.
- read_char_code() = : This function reads a single UTF-8 character from and returns its code point. It returns -1 if is at the end of the file.
- read_char_code()=: This function is the same as read_char_code(stdin).
- read_char_code(, ) = : This function reads up to UTF-8 characters from . It returns a list of code points of the characters that were read.
- read_file_bytes() = : This function reads an entire byte file into a list.
- read_file_bytes() = : This function reads an entire byte file from the console into a list.
- read_file_chars() = : This function reads an entire character file into a string.
- read_file_chars() = : This function reads an entire character file from the console into a string.
- read_file_codes() = : This function reads UTF-8 codes of an entire character file into a list.
- read_file_codes() = : This function reads UTF-8 codes of an entire character file from the console into a list.
- read_file_lines() = : This function reads an entire character file into a list of line strings.
- read_file_lines() = : This function reads an entire character file from the console into a list of line strings.
- read_file_terms() = : This function reads an entire text file into a list of terms. In the file, each term must be terminated by ‘.’ followed by at least one whitespace character.
- read_file_terms() = : This function reads an entire text file from the console into a list of terms.
- read_int() = : This function reads a single integer from .
- read_int() = : This function is the same as read_int(stdin).
- read_line() = : This function reads a line from , excluding the terminating newline (‘rn’ on Windows, and ‘n’ on Unix). It returns end_of_file if is already at the end of the file.
- read_line() = : This function is the same as read_line(stdin).
- readln() = : This function does the same thing as read_line().
- readln() = : This function is the same as readln(stdin).
- read_number() = : This function reads a single number (an integer or a real number) from .
- read_number() = : This function is the same as read_number(stdin).
-
read_picat_token(, , ): This predicate reads a single Picat token from . is the type and is the value of the token. is one of the following:
- atom
- end_of_file
- end_of_rule
- integer
- punctuation
- real
- string
- underscore
- var
- read_picat_token(, ): This predicate reads a token from stdin.
- read_picat_token() = : This function reads a single Picat token from and returns the token value.
- read_picat_token() = : This function is the same as the above, except that it reads from stdin.
- read_real() = : This function reads a single real number from .
- read_real() = : This function is the same as read_real(stdin).
- read_term() = : This function reads a single Picat term from . The term must be followed by a dot ‘.’ and at least one whitespace character. This function consumes the dot symbol. The whitespace character is not stored in the returned term. It returns end_of_file if is at the end of the file.
- read_term() = : This function is the same as read_term(stdin).
The bulk-read functions, including read_byte(, ), read_char(, ), and read_char_code(, ), may read fewer than 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 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() 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.
- write(, ): This predicate writes to a file. Strings are written as lists of single-character atoms. Atoms are single-quoted when necessary. This predicate does not print a newline, meaning that the next write will begin on the same line.
- write(): This predicate is the same as write(stdout, ).
- write_byte(, ): This predicate writes a single byte or a list of bytes to a file.
- write_byte(): This predicate is the same as write_byte(stdout, ).
- write_char(, ): This predicate writes a single character or a list of characters to a file. The characters are not quoted. When writing a single-character atom , write_char(, ) is the same as print(, ), but write_char is faster than print.
- write_char(): This predicate is the same as write_char(stdout,).
- write_char_code(, ): This predicate writes a single character or a list of characters of the given code or list of codes to a file.
- write_char_code(): This predicate is the same as the above, except that it writes to stdout.
- writef(, , ): This predicate is used for formatted writing, where the parameter contains format characters that indicate how to print each of the arguments in the parameter. The number of arguments in cannot exceed 16.
- writeln(, ): This predicate writes and a newline, meaning that the next write will begin on the next line.
- writeln(): This predicate is the same as writeln(stdout, ).
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 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.
- print(, ): This predicate prints to a file. Unlike the write predicates, the print predicates do not place quotes around strings and atoms.
- print(): This predicate is the same as print(stdout, ).
- printf(, , ): This predicate is the same as writef, except that printf uses print to display the arguments in the parameter, while writef uses write to display the arguments in the parameter. The number of arguments in cannot exceed 16.
- println(, ): This predicate prints and a newline.
- println(): This predicate is the same as println(stdout, ).
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.
- flush(): This predicate causes all buffered data to be written without delay.
- close(): This predicate causes the file to be closed, releasing the file’s resources, and removing the file from the file descriptor table. Any further attempts to write to the file descriptor without calling open will cause an error to be thrown.
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.