Why can Ruby's File#read
and File#readlines
only be used once?
For example:
txt = File.open "test.txt"
puts txt.read # returns the content
puts txt.read # returns ""
When you call File.open
you are opening an I/O stream to the file. Internally, the stream has a "cursor," which represents what part of it you read from last. When you call File#read
with no length argument, it reads from the cursor (which starts at the beginning of the file when you open it) until the end of the stream, i.e. the end of the file. In so doing, the cursor is also moved to the end of the file. If you call read
again, then, the cursor is still at the end of the file, and since there is nothing more for it to read it returns nothing (""
).
If you need to read the file a second time you can move the cursor back to the beginning of the stream using File#rewind
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With