How to read all lines from stdin in Clojure

I am writing a Brainf *** interpreter in Clojure. I want to pass the program in using stdin. However, I still need to read from stdin later for user input.

I am currently doing this:

$ cat sample_programs/hello_world.bf | lein trampoline run 

My Clojure code reads only the first line using read-line :

 (defn -main "Read a BF program from stdin and evaluate it." [] ;; FIXME: only reads the first line from stdin (eval-program (read-line))) 

How can I read all the lines in the file that I entered? *in* seems to be an instance of java.io.Reader , but it only provides .read (one char), .readLine (one line) and read(char[] cbuf, int off, int len) (seems very low).

+6
source share
2 answers

you can get a lazy row of lines from *in* as follows:

 (take-while identity (repeatedly #(.readLine *in*))) 

or that:

 (line-seq (java.io.BufferedReader. *in*)) 

which are functionally identical.

+8
source

It is enough to simply read all the input data as a single line:

 (defn -main [] (let [in (slurp *in*)] (println in))) 

This works great if your file can fit in available memory; to read large files lazily, see this answer .

+8
source

All Articles