JanetDocsPlaygroundI'm feeling luckyGitHub sign in


    src/core/io.c on line 217, column 1

    (file/read f what &opt buf)

    Read a number of bytes from a file `f` into a buffer. A buffer 
    `buf` can be provided as an optional third argument, otherwise a 
    new buffer is created. `what` can either be an integer or a 
    keyword. Returns the buffer with file contents. Values for `what`:

    * :all - read the whole file

    * :line - read up to and including the next newline character

    * n (integer) - read up to n bytes from the file

See also:slurp4 examplesSign in to add an example
# Reading a file line by line, using loop's :iterate verb, and adding the line lengths

(with [fl (file/open "filepath")]
  (var sm 0)
  (loop [line :iterate (file/read fl :line)]
    (+= sm (length line)))

### read a file line by line ###

(let [f (file/open "filename.txt")] # bind an open file handle to "f"
  (while true                       # loop until "break" is called
    (let [l (file/read f :line)]    # bind a line of the file to "l" 
      (if l                         
	(print l)                   # if l is truthy print l
	(break))))                  # if l is not break from loop
  (file/close f))                   # close the file handle 

# same as above but using "with"
# this means there's no need to 
# call file/close, also replace
# let with var
(with [f (file/open "filename.txt")]
      (while true
	(var l (file/read f :line))
	(if l
	  (print l)
(defn read-from-file [file-path]
  (let [f (file/open file-path :r)
        content  (file/read f :all)]
    (file/close f)

### USAGE 

(read-from-file "/path/to/file-read-example.janet")
# => @"(defn read-from-file [file-path]\n  (let [f (file/open file-path :r)\n        content  (file/read f :all)]\n    (file/close f)\n    content))\n"
#!/usr/bin/env janet
# echo stdin to stdout.
(file/write stdout (file/read stdin :all))