mark
mark

Reputation: 873

Read from a file and return output in a vector

I'm just learning clojure and trying to read in a file and do something with the returned vector of results. In this instance I'm just trying to print it out.

Below is the code in question:

(defn read_file
  "Read in a file from the resources directory"
  [input]
  (with-open [rdr (reader input)]
    (doseq [line (line-seq rdr)])))

(defn -main []
  (println (read_file "resources/input.txt") ))

The println returns a "nil". What do I need to do to return "line"

Upvotes: 1

Views: 1268

Answers (2)

omiel
omiel

Reputation: 1593

doseq returns nil. It's supposed to be used when you're doing stuff in a do fashion on the elements of a sequence, so mostly side-effect stuff.

Try this:

(defn file->vec
  "Read in a file from the resources directory"
  [input]
  (with-open [rdr (reader input)]
    (into [] (line-seq rdr))))

But you shouldn't do this for big files, in those cases you don't want the whole file to sit in memory. For this reason, slurp is equally bad.

Upvotes: 2

ntalbs
ntalbs

Reputation: 29438

If the file is not very big, you can use slurp to read the file content as a string, then split it with a specific delimiter (in this case \n).

(defn read-file [f]
  (-> (slurp f)
      (clojure.string/split-lines)))

Upvotes: 5

Related Questions