How to read a file in Crystal?
Asked Answered
M

1

5

I recently picked up on Crystal after being a Rubyist for a while, and I can't seem to find anything about the File class. I want to open and read a file, but it gives me an error.

file = File.open("ditto.txt")
file = file.read
tequila@tequila-pc:~/code$ crystal fileopen.cr
Error in fileopen.cr:2: wrong number of arguments for 'File#read' (given 0, expected 1)
Overloads are:
 - IO::Buffered#read(slice : Bytes)
 - IO#read(slice : Bytes)

file = file.read
            ^~~~
Mavismavra answered 25/4, 2019 at 15:17 Comment(1)
Note that the error message also says IO#read(slice : Bytes) File inherits the read method from IO. According to the docs for IO#read it expects an argument. You might want to try the File.read class method instead.Paton
B
8

You're probably looking for IO#gets_to_end which reads the entire file as a String. But you might as well use File.read

file_content = File.read("ditto.txt")

IO#read is a different, more low-level method which allows to read pieces of an IO into a byte slice.

Bunny answered 25/4, 2019 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.