From 64e3cdeb2b37dd1b03d35ad211327cff1980f964 Mon Sep 17 00:00:00 2001 From: Ico Doornekamp Date: Wed, 24 May 2023 16:39:49 +0200 Subject: [PATCH] Add file/lines iterator --- src/boot/boot.janet | 13 +++++++++++++ test/suite0009.janet | 13 +++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/boot/boot.janet b/src/boot/boot.janet index a6097660..bf39ce44 100644 --- a/src/boot/boot.janet +++ b/src/boot/boot.janet @@ -1749,6 +1749,19 @@ (printf (dyn *pretty-format* "%q") x) (flush)) +(defn file/lines + "Return an iterator over the lines of a file" + [file-or-path &opt mode] + (default mode :r) + (if (bytes? file-or-path) + (coro + (with [f (file/open file-or-path mode)] + (while (def line (file/read f :line)) + (yield line)))) + (coro + (while (def line (file/read file-or-path :line)) + (yield line))))) + ### ### ### Pattern Matching diff --git a/test/suite0009.janet b/test/suite0009.janet index 99f5232e..2b9b2205 100644 --- a/test/suite0009.janet +++ b/test/suite0009.janet @@ -102,6 +102,19 @@ (os/execute [janet "-e" `(repeat 20 (print :hello))`] :p {:out f}) (file/flush f))) +# each-line iterator + +(assert-no-error "file/lines iterator" + (def outstream (os/open "unique.txt" :wct)) + (def buf1 "123\n456\n") + (defer (:close outstream) + (:write outstream buf1)) + (var buf2 "") + (each line (file/lines "unique.txt") + (set buf2 (string buf2 line))) + (assert (= buf1 buf2) "file/lines iterator") + (os/rm "unique.txt")) + # Issue #593 (assert-no-error "file writing 3" (def outfile (file/open "unique.txt" :w))