LISP 簡單的資料庫 3.5 儲存和載入資料庫
阿新 • • 發佈:2019-02-02
將*DB*中的資料資訊儲存到檔案中,以及可以從檔案中讀取資料資訊放置到*DB*全域性變數中
新增兩個函式 save-db 及 load-db
;使用全域性變數記錄資料 (defvar *db* nil) ;資料記錄格式 (defun make-cd (title artist rating ripped) (list :title title :artits artist :rating rating :ripped ripped) ) ;新增記錄 (defun add-record (cd) ( push cd *db*) ) ;檢視資料庫內容 (defun dump-db() (dolist (cd *db*) (format t "~{~a: ~10t~a~%~}~%" cd)) ) ;提示使用者輸入CD資訊 (defun prompt-read (prompt) (format *query-io* "~a: " prompt) (force-output *query-io*) (read-line *query-io*) ) ;依次提示使用者輸入資訊 (defun prompt-for-cd() (make-cd (prompt-read "Title") (prompt-read "Artist") ;(prompt-read "Rating") ;(prompt-read "Ripped [y/n]") ;快餐式驗證資料有效性 (or (parse-integer (prompt-read "Rating") :junk-allowed t) 0) (y-or-n-p "Ripped [y/n]: ") ) ) ;批量新增資料,使用回車退出 (defun add-cds() (loop (add-record (prompt-for-cd)) (if (not (y-or-n-p "Another? [y/n]:")) (return) ) ) ) ;儲存資料 (defun save-db (filename) (with-open-file(out filename :direction :output :if-exists :supersede) (with-standard-io-syntax(print *db* out)) ) ) ;載入資料 (defun load-db(filename) (with-open-file(in filename) (with-standard-io-syntax(setf *db* (read in))) ) )
(save-db "d:/1.db")
(load-db "d:/1.db")
注:目前儲存資料不支援中文