## 9   Input and Output

### 9.1   Input Output commands

At this time we have seen how we can communicate with prolog using the keyboard and the screen. We will now see how we can communicate with prolog using files.

Prolog can read and write in a file. The file where Prolog read is called input and the file where Prolog write is called output. When you run Prolog the default output is your screen (the shell) and the input is your keyboard. If you want to use files for thatr you have to tell it to Prolog using the commands listed in the appendix on this page.

### 9.2   Read and Write

readwrite Sometimes a program will nedd to to read a term from a file or the keybord and write a term on the screen or in a file. In this case the goals write and read can be used.
Read the term from the active input and unifie X with it.
write(Y).
Write the term Y on the active output.

### 9.3   Examples

#### 9.3.1   Calculating the cube of an integer

If we have the following program :
```
cube(C,N) :- C is N * N * N

```
If you ask something like cube(X,3). then Prolog would respond X=9. Suppose that we want to ask for other values than 3, we could write this program like this :
```
cube :-
read(X), calc(X).  /* read X then query calc(X). */

calc(stop) :- !.           /* if X = stop then it ends   */

calc(X) :- C is X * X * X, write(C),cube.
/* calculate C and write it then ask again cube. */

```
Now if we ask Prolog cube, Prolog will ask use a value and give us the result until we write stop.

#### 9.3.2   Treating the terms of a file

If we wanted to treat each term of a file, we could use this query :
```
?- see(filename), treatfile.\index{see(filename)}

```
using the following program :read(Term)
```
treatfile :- read(Term), treat(Term).

treat( end_of_file ) :- !.

treat(Term) :- treatterm(Term),treatfile.

treatterm :- [the treatment you want to do to each term.]

```

#### 9.3.3   ASCII characters

It is of course possible to use ASCII code in Prolog. For example if you type :
```
?- put(65), put(66), put(67).

```
Prolog will write ABC.

#### 9.3.4   Using Another Program

It is possible to load another Prolog program using a program. Two predicates have been made for this : consult(program1) to add in the database all the predicates contained in program1 amd reconsult(program2) to reload the predicates contained in program2.

 - SWI-Prolog -->