Previous Up Next

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.

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.


The fclose command closes a file.


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)

Previous Up Next