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?
How about
(defun get-file (filename)
(with-open-file (stream filename)
(loop for line = (read-line stream nil)
while line
collect line)))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With