To open a file for input, use the open function with the keyword argument :direction set to :input. To open a file for output, use the open function with the keyword argument :direction set to :output. The open function takes a single required argument which is the name of the file to be opened. This name can be in the form of a string or a symbol. The open function returns an object of type 'file-stream' if it succeeds in opening the specified file. It returns the value NIL if it fails.
In order to manipulate the file, it is necessary to save the value returned by the open function. This is usually done by assigning it to a variable with the setq special form or by binding it using let or let*. Here is an example:
(setq fp (open "init.lsp" :direction :input))
Evaluating this expression will result in the file 'init.lsp' being opened. The file object that will be returned by the open function will be assigned to the variable 'fp'.
It is now possible to use the file for input. To read an expression from the file, just supply the value of the 'fp' variable as the optional 'stream' argument to the read function:
(read fp)
Evaluating this expression will result in reading the first expression from the file 'init.lsp'. The expression will be returned as the result of the read function. More expressions can be read from the file using further calls to the read function. When there are no more expressions to read, the read function will return NIL [or whatever value was supplied as the second argument to read].
Once you are done reading from the file, you should close it. To close the file, use the close function:
(close fp)
Evaluating this expression will cause the file to be closed.
Writing to a file is pretty much the same as reading from one. You need to open the file first. This time you should use the open function to indicate that you will do output to the file. For example:
(setq fp (open "test.dat" :direction :output))
Evaluating this expression will open the file 'test.dat' for output. If the file already exists, its current contents will be discarded. If it doesn't already exist, it will be created. In any case, a 'file-stream' object will be returned by the open function. This file object will be assigned to the 'fp' variable.
It is now possible to write to this file by supplying the value of the 'fp' variable as the optional 'stream' parameter in the print function.
(print "Hello there" fp)
Evaluating this expression will result in the string
Once you are done writing to the file, you should close it. Closing an output file is just like closing an input file:
(close fp)
Evaluating this expression will close the output file and make it permanent.
This example shows how to open a file, read each Lisp expression from the file and print it. It demonstrates the use of files and the use of the optional 'stream' argument to the read function.
(do* ((fp (open "test.dat" :direction :input)) (ex (read fp) (read fp))) ((null ex) nil) (print ex))