# Writing output to a file: fopen fclose fprint

### 12.4.4 Writing output to a file: fopen fclose fprint

You can use the fopen, fprint and fclose commands to write output to a file instead of the screen.

The fopen command creates and opens a file to write into.

- fopen takes one argument:
  filename, a string.
- fopen(filename) creates a file named filename (and erases it if it already exists).

To use this, you need to associate it with a variable var:=fopen(filename) which you can use to refer to the file when printing to it.

The fprint command writes to a file.

- fprint takes two mandatory arguments and one optional argument:
  - var, a variable name associated with a file through fopen.
  - Optionally, Unquoted, the symbol.
  - info, a list of what you want to write to the file.
- fprint(var ⟨ Unquote ⟩,info) writes info into the file given by var. By default, strings in info are written with their quotation marks, with the option Unquoted, fprint will print them with the quotation marks.

The fclose command closes a file.

- fclose takes one argument:
  var, a variable assigned to a file with fopen.
- fclose(var) closes the file given by var to further writing.

#### Example.

To write contents to a file, you first need to open the file and associate it with a variable.
Input:

f:= fopen("bar")

This creates a file named “bar” (and so erase it if it already exists). To write to the file:
Input:

x:=9
fprint(f,"x + 1 is ", x+1)

will put

"x + 1 is "10

in the file. Note that the quotation marks are inserted with the Unquoted argument:
Input:

x:=9
fprint(f,Unquoted,"x + 1 is ", x+1)

will put

x + 1 is 10

in the file. Finally, after you have finished writing what you want into the file, you close the file with the fclose command:
Input:

fclose(f)