如何在Crystal中读取文件?

问题描述 投票:1回答:1

我最近在成为Rubyist之后接受了Crystal,我似乎无法找到关于File类的任何内容。我想打开并读取一个文件,但它给了我一个错误。

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
            ^~~~
file methods crystal-lang
1个回答
3
投票

你可能正在寻找IO#gets_to_end,它将整个文件读作String。但你不妨使用File.read

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

IO#read是一种更低级的方法,它允许将IO的片段读入字节片。

© www.soinside.com 2019 - 2024. All rights reserved.