teq*_*ila 2 methods file crystal-lang
在成为 Rubyist 一段时间后,我最近开始使用 Crystal,但我似乎找不到关于 File 类的任何信息。我想打开并读取一个文件,但它给了我一个错误。
file = File.open("ditto.txt")
file = file.read
Run Code Online (Sandbox Code Playgroud)
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
^~~~
Run Code Online (Sandbox Code Playgroud)
您可能正在寻找IO#gets_to_end将整个文件读取为String. 但你也可以使用File.read
file_content = File.read("ditto.txt")
Run Code Online (Sandbox Code Playgroud)
IO#read 是一种更底层的方法,它允许将 IO 的片段读入字节切片。