用于简单 I/O 的方法也可用于所有 file 对象。所以,gets 从标准输入读取一行,aFile.gets 从文件对象 aFile 读取一行。
但是,I/O 对象提供了访问方法的附加设置,为我们提供了便利。
content = aFile.sysread(num)
模式 | 描述 |
---|---|
aFile | 文件对象。 |
num | 读取的字节数。 |
content | 读取的文件内容。 |
使用 sysread 读取文件的前 num 个字符。
使用 sysread 方法读文件
#!/usr/bin/ruby -w
# -*- coding : utf-8 -*-
puts "HaiCoder(www.haicoder.net)"
aFile = File.new("input.txt", "r")
if aFile
content = aFile.sysread(20)
puts content
else
puts "Unable to open file!"
end
程序运行后,控制台输出如下:
使用 sysread 方法读取文件的前 20 个字符。
用于简单 I/O 的方法也可用于所有 file 对象。所以,gets 从标准输入读取一行,aFile.gets 从文件对象 aFile 读取一行。