Prev: need easy benchmarks
Next: Lisp sucks!
From: Vinay on 11 Mar 2010 22:06 i need to create a string containing the contents of a stream until i reach eof. can anyone show me how this is done. i found this in the cl cookbook ... (with-open-file (stream "/etc/passwd") (do ((line (read-line stream nil) (read-line stream nil))) ((null line)) (print line))) i need to accumulate the lines being read into a single string ...
From: Vassil Nikolov on 11 Mar 2010 22:53 On Thu, 11 Mar 2010 19:06:12 -0800, Vinay <vinay(a)vmmenon.org> said: > i need to create a string containing the contents of a stream until i > reach eof. > ... > (with-open-file (stream "/etc/passwd") > (do ((line (read-line stream nil) > (read-line stream nil))) > ((null line)) > (print line))) Do the above inside WITH-OUTPUT-TO-STRING, writing everything read to the string output stream. By the way, consider also something along the lines of (loop for line = (read-line stream nil) while line do (print line)) ---Vassil. -- No flies need shaving.
From: refun on 11 Mar 2010 22:58 Here's another way using a fill-pointer: (defun read-stream-to-string (stream) (let ((string (make-array (file-length stream) :element-type 'character :initial-element #\Space :fill-pointer 0))) (loop for char = (read-char stream nil 'done) until (eql char 'done) do (vector-push char string) finally (return string)))) (with-open-file (s #p"path goes here") (read-stream-to-string s)) It makes an array of file-length size, but keeps a fill-pointer of 0, then pushes each character into the array. Is this the way to keep down the consing and avoid copying the array data pointlessly?
From: Vassil Nikolov on 11 Mar 2010 23:12 On Fri, 12 Mar 2010 03:58:53 +0000 (UTC), refun <refun(a)nospam.gmx.com> said: > Here's another way using a fill-pointer: > (defun read-stream-to-string (stream) > (let ((string (make-array (file-length stream) > :element-type 'character > :initial-element #\Space > :fill-pointer 0))) > (loop for char = (read-char stream nil 'done) > until (eql char 'done) > do (vector-push char string) > finally (return string)))) Change to ``(OR (FILE-LENGTH STREAM) 0)'', add ``:ADJUSTABLE T'', and use VECTOR-PUSH-EXTEND to degrade gracefully when the input stream's length cannot be determined or when the file grows while being read. ---Vassil. -- No flies need shaving.
From: milanj on 12 Mar 2010 03:10
what about using something like this: (let ((string (make-array (file-stream stream) :element-type 'character))) (read-sequence string stream) (string)) |