Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read the contents of a file into a list in Lisp?

I want to read in the contents of a file into a list. Some of my attempts so far have been -

(defun get-file (filename)
  (let ((x (open filename)))
    (when x
      (loop for line = (read-line x nil)
     while line do (list line)))
    (close x)))

(defun get-file (filename)
  (let ((x (open filename :if-does-not-exist nil)) (contents (list nil)))
    (when x
      (loop for line = (read-line x nil)
     while line do (cons contents line)))
    (close x) contents))

(defun get-file (filename)
  (let ((x (open filename :if-does-not-exist nil)) (contents nil))
    (when x
      (loop for line = (read-line x nil)
     while line do (append contents line)))
    (close x) contents))

None of these worked. Can anyone tell me a way? Or even better - how to put all of the contents into an array?

like image 833
Sterling Avatar asked Sep 28 '10 14:09

Sterling


2 Answers

How about

(defun get-file (filename)
  (with-open-file (stream filename)
    (loop for line = (read-line stream nil)
          while line
          collect line)))
like image 102
Frank Shearar Avatar answered Oct 24 '22 02:10

Frank Shearar


I'll add libraries in.

edit even easier, with uiop, which is included in ASDF:

(uiop:read-file-lines "file.txt")

https://common-lisp.net/project/asdf/uiop.html#UIOP_002fSTREAM

also has

(uiop:read-file-string "file")

With Alexandria's read-file-into-string and split-sequence:

(alexandria:read-file-into-string "file.txt")
(split-sequence:split-sequence #\Newline *)

With str:

(str:lines (str:from-file "file.txt"))

More recipes on files: https://lispcookbook.github.io/cl-cookbook/files.html

like image 22
Ehvince Avatar answered Oct 24 '22 03:10

Ehvince