用于简单 I/O 的方法也可用于所有 file 对象。所以,gets 从标准输入读取一行,aFile.gets 从文件对象 aFile 读取一行。
sysread 方法
下面是输入文本文件:
This is a simple text file for testing purpose.
现在让我们尝试读取这个文件:
实例
#!/usr/bin/ruby
aFile = File.new("input.txt", "r")
if aFile
content = aFile.sysread(20)
puts content
else
puts "Unable to open file!"
end
该语句将输入文件的头 20 个字符。文件指针将被放置在文件中第 21 个字符的位置。
syswrite 方法
您可以使用方法 syswrite 来向文件写入内容。当使用方法 syswrite 时,您需要以写入模式打开文件。例如:
实例
#!/usr/bin/ruby
aFile = File.new("input.txt", "r+")
if aFile
aFile.syswrite("ABCDEF")
else
puts "Unable to open file!"
end
该语句将写入 “ABCDEF” 到文件中。
each_byte 方法
该方法属于类 F