(require racket/port) is needed for #lang racket/base.
For these examples, say you have two files in the same directory as your program, "oneline.txt" and "manylines.txt".
"oneline.txt"
I am one line, but there is an empty line after this one.
"manylines.txt"
I am
a message
split over a few lines.
If you have a file that is quite small, you can get away with reading in the file as a string:
#f
#t
#t
We use port->string from racket/port to do the reading to a string: the #:close?#t keyword argument ensures that our file is closed after the read.
We use string-trim from racket/string to remove any extraneous whitespace at the very beginning and very end of our file. (Lots of formatters out there insist that text files end with a single blank line).
See also read-line if your file has one line of text.
If, instead, you want to process individual lines of a file, then you can use for with in-lines :
HELLO, WORLD!
CAN YOU HEAR ME, NOW?
You could also combine computations over each line. So if you want to know how many lines contain “m”, you could do:
1)))2
Here, with-input-from-file from racket/port sets the default input port to be the file "manylines.txt" inside the thunk. It also closes the file after the computation has been completed (and in a few other cases).
However, if you want to determine whether “hello” appears in a file, then you could search separate lines, but it’s even easier to simply apply a regular expression (see Regular Expressions) to the stream:
#t
#f
If you want to copy one port into another, use copy-port from racket/port, which efficiently transfers large blocks when lots of data is available, but also transfers small blocks immediately if that’s all that is available:
"broom"