Ruby读文件

用于简单 I/O 的方法也可用于所有 file 对象。所以,gets 从标准输入读取一行,aFile.gets 从文件对象 aFile 读取一行。

但是,I/O 对象提供了访问方法的附加设置,为我们提供了便利。

sysread方法

语法

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

程序运行后,控制台输出如下:

05_Ruby读文件.png

使用 sysread 方法读取文件的前 20 个字符。

Ruby读文件

用于简单 I/O 的方法也可用于所有 file 对象。所以,gets 从标准输入读取一行,aFile.gets 从文件对象 aFile 读取一行。