Friday, October 9, 2009

Files and File I/O In Common Lisp

Reading File Data(Notes from Practical Common Lisp)

You obtain a stream from which you can read a file's contents with the open function. By default open function returns character-based input stream you can pass to a variety of functions that read one or more characters of text:read-char reads a single character;read-line read a line of text,returning it as string with the end-of-line character removed;and READ reads a single s-expression, returning a Lisp object. When you’re done with the stream, you can close it with the CLOSE function.
(let ((in (open "/some/file/name.txt")))
    (format t "~a~%" (read-line in))
    (close in))
You can add some options to modify the behaver.If you want to open a possibly nonexistent file without OPEN signaling an error, you can use the keyword argument :if-does-not-exist to specify a different behavior. The three possible values are :error, the default; :create, which tells it to go ahead and create the file and then proceed as if it had already existed; and NIL, which tells it to return NIL instead of a stream.
Of these three read-* functions, the read is unique to Lisp which is can be used to read the source code of Lisp.
File Output
Common Lisp also provides several functions for writing data: WRITE-CHAR writes a single character to the stream. WRITE-LINE writes a string followed by a newline, which will be output as the appropriate end-of-line character or characters for the platform. Another function,WRITE-STRING, writes a string without adding any end-of-line characters.
Two different functions can print just a newline: TERPRI—short for “terminate print”—unconditionally prints a newline character, and FRESH-LINE prints a newline character unless the stream is at the beginning of a line.
(with-open-file (stream-var open-argument*)
    body-form*)
This is a macro which can make sure that it would close the file, you do not need close the file manually.Like the Using in the C#.

No comments:

Post a Comment