Open file explanation to lay people

I study CL and I have minimal experience in other languages. Can anyone explain to me in unprofessional terms what this means, especially what is β€œoutside” here, and how it all fits together:

(defun save-db (filename) (with-open-file (out filename :direction :output :if-exists :supersede) (with-standard-io-syntax (print *db* out)))) 

Basically, a bit that I don't understand is β€œoutside”, but an explanation of all this would be nice.

thanks

+7
lisp common-lisp
source share
2 answers

out is a stream variable associated with an open file. with-open-file ensures that the file is open inside the scope and closed outside the scope, regardless of how you exit.

+5
source share

As an addition to ddyer, you can also use MACROEXPAND or MACROEXPAND-1 to find out what WITH-OPEN-FILE does:

 (macroexpand '(with-open-file (out filename :direction :output :if-exists :supersede) (with-standard-io-syntax (print *db* out)))) 

informs us

 (LET ((OUT (OPEN FILENAME :DIRECTION :OUTPUT :IF-EXISTS :SUPERSEDE)) (#:G748 T)) (UNWIND-PROTECT (MULTIPLE-VALUE-PROG1 (PROGN (WITH-STANDARD-IO-SYNTAX (PRINT *DB* OUT))) (SETQ #:G748 NIL)) (WHEN OUT (CLOSE OUT :ABORT #:G748)))) 

We see that we open a file with the name filename and assign this open file stream out and do something. If something bad UNWIND-PROTECT , UNWIND-PROTECT will CLOSE thread if it was not nil .

Variable #:G748 is a GENSYM ed character (so this is a new, uninterrupted character). If all else fails, write a file, we will set #:G748 to nil .

Thus, when we CLOSE stream, if something went wrong, #:G748 will be T , so CLOSE will try to clear any side effects from creating the stream.

+1
source share

All Articles