首页 > 解决方案 > 如何在 Crystal 中读取文件?

问题描述

在成为 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
            ^~~~

标签: filemethodscrystal-lang

解决方案


您可能正在寻找IO#gets_to_end将整个文件读取为String. 但你不妨使用File.read

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

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


推荐阅读