`

ruby way之IO

    博客分类:
  • RUBY
 
阅读更多
ruby文件读写的好文章 ruby way之IO

1 打开和关闭一个文件
类方法File.new 打开一个文件,并将它实例化为一个File对象,他的第一个参数是文件名.
可选的第二个参数叫做 mode string(这个也是从c得来的).他的意思是怎样打开一个文件(读,写或者其他的).默认是'r'(也就是读).
Ruby代码
file1 = File.new("one")       # Open for reading  
  
file2 = File.new("two", "w")  # Open for writing  

file1 = File.new("one")       # Open for reading  file2 = File.new("two", "w")  # Open for writing
另外一种new的形式是三个参数的,其中第二个参数是指定了这个文件的原始的权限(经常表示为一个八进制的数).第三个参数是一系列Ored标志 的组合.标志是个常量比如File:CREAT(如果文件不存在则创建它)和File:RDONLY(以只读方式打开文件)。不过这种形式很少使用:

Ruby代码
file = File.new("three", 0755, File::CREAT|File::WRONLY)  

file = File.new("three", 0755, File::CREAT|File::WRONLY)


出于对操作系统和运行环境的考虑,如果你打开了一个文件的话,你就必须关闭它。当你打开一个文件用于写时,你更应该这样做,从而才能免于丢失数据.close方法就是关闭一个文件:

Ruby代码
out = File.new("captains.log", "w")  
# Process as needed...  
out.close  

out = File.new("captains.log", "w") # Process as needed... out.close

这里还有一个open方法,它的最简单的形式是和new同义的:
Ruby代码
trans = File.open("transactions","w")  

trans = File.open("transactions","w")


但是open方法还能够带一个block作为参数,当存在block时,打开的文件将会做为一个参数传递给block.这时这个文件将会在这个block的作用域里,保持打开,直到block结束时,自动关闭:

Ruby代码
File.open("somefile","w") do |file|  
   file.puts "Line 1"  
   file.puts "Line 2"  
   file.puts "Third and final line"  
end  

File.open("somefile","w") do |file|   file.puts "Line 1"   file.puts "Line 2"   file.puts "Third and final line" end


2 更新文件

假设我们想要打开一个文件用于读和写,简单的加一个'+'号到file mode就行了:
Ruby代码
f1 = File.new("file1", "r+")  
# Read/write, starting at beginning of file.  
f2 = File.new("file2", "w+")  
# Read/write; truncate existing file or create a new one.  
f3 = File.new("file3", "a+")  
# Read/write; start at end of existing file or create a  
# new one.  

f1 = File.new("file1", "r+") # Read/write, starting at beginning of file. f2 = File.new("file2", "w+") # Read/write; truncate existing file or create a new one. f3 = File.new("file3", "a+") # Read/write; start at end of existing file or create a # new one.


3 追加一个文件

假设我们想要追加一段信息到一个存在文件,当我们打开文件时使用'a'作为file mode就行了:

Ruby代码
logfile = File.open("captains_log", "a")  
# Add a line at the end, then close.  
logfile.puts "Stardate 47824.1: Our show has been canceled."  
logfile.close  

logfile = File.open("captains_log", "a") # Add a line at the end, then close. logfile.puts "Stardate 47824.1: Our show has been canceled." logfile.close


4随机存取一个文件

如果你想随即存取一个文件,你能够使用seek方法,它是File从Io继承而来的.它的最简单的使用就是指定一个字节位置.这个位置是相对于文件开始的位置(开始的位置是0):
Ruby代码
# myfile contains only: abcdefghi  
file = File.new("myfile")  
file.seek(5)  
str = file.gets                   # "fghi"  

# myfile contains only: abcdefghi file = File.new("myfile") file.seek(5) str = file.gets                   # "fghi"


如果你能确定每一行都是固定的长度,你就能seek指定的行:
Ruby代码
# Assume 20 bytes per line.  
# Line N starts at byte (N-1)*20  
file = File.new("fixedlines")  
file.seek(5*20)                   # Sixth line!  
# Elegance is left as an exercise.  

# Assume 20 bytes per line. # Line N starts at byte (N-1)*20 file = File.new("fixedlines") file.seek(5*20)                   # Sixth line! # Elegance is left as an exercise.
如果你想做一个相对的搜索,你就要使用第二个参数,常量 IO::SEEK_CUR表示当前的位置,而第一个参数则就是相对于当前位置的偏移量(可能是负数):

Ruby代码
file = File.new("somefile")  
file.seek(55)                 # Position is 55  
file.seek(-22, IO::SEEK_CUR)  # Position is 33  
file.seek(47, IO::SEEK_CUR)   # Position is 80  

file = File.new("somefile") file.seek(55)                 # Position is 55 file.seek(-22, IO::SEEK_CUR)  # Position is 33 file.seek(47, IO::SEEK_CUR)   # Position is 80


你也能从文件的结束位置开始搜索:

Ruby代码
file.seek(-20, IO::SEEK_END)  # twenty bytes from eof  

file.seek(-20, IO::SEEK_END)  # twenty bytes from eof
方法tell得到文件的当前位置,pos是它的别名:

Ruby代码
file.seek(20)  
pos1 = file.tell             # 20  
file.seek(50, IO::SEEK_CUR)  
pos2 = file.pos              # 70  

file.seek(20) pos1 = file.tell             # 20 file.seek(50, IO::SEEK_CUR) pos2 = file.pos              # 70
rewind方法将会将文件指针的位置设回到开始的位置,也就是0.

5 操作二进制文件

在很久以前,c语言通过在file mode后附加一个'b'来表示将文件用二进制模式打开.在今天,二进制文件的处理已经没有那么麻烦了。在ruby中,一个字符串很容易保存一个二进制数据,而且也不用通过任何特殊的方式来读文件.

可是在windows下是例外,在他下面,二进制文件和文本文件的不同是,在二进制mode下,结束行不能被转义为一个单独的换行,而是被保存为一个回车换行对.
另外的不同是,在文本模式下 control-Z被作为文件的结束:

Ruby代码
# Create a file (in binary mode)  
File.open("myfile","wb") {|f| f.syswrite("12345\0326789\r") }  
# Above note the embedded octal 032 (^Z)  
# Read it as binary  
str = nil  
  
File.open("myfile","rb") {|f| str = f.sysread(15) }  
puts str.size           # 11  
# Read it as text  
str = nil  
File.open("myfile","r") {|f| str = f.sysread(15) }  
puts str.size           # 5  

# Create a file (in binary mode) File.open("myfile","wb") {|f| f.syswrite("12345\0326789\r") } # Above note the embedded octal 032 (^Z) # Read it as binary str = nil  File.open("myfile","rb") {|f| str = f.sysread(15) } puts str.size           # 11 # Read it as text str = nil File.open("myfile","r") {|f| str = f.sysread(15) } puts str.size           # 5
这边注意,这些代码都是在windows下才会打印出后面的结果,如果是在linux两处都会打印出11.
再看下面的代码:
Ruby代码
# Input file contains a single line: Line 1.  
file = File.open("data")  
line = file.readline             # "Line 1.\n"  
puts "#{line.size} characters."   # 8 characters  
file.close  
file = File.open("data","rb")  
line = file.readline             # "Line 1.\r\n"  
puts "#{line.size} characters."   # 9 characters 二进制模式的结尾是一个回车换行对.  
file.close  

# Input file contains a single line: Line 1. file = File.open("data") line = file.readline             # "Line 1.\n" puts "#{line.size} characters."  # 8 characters file.close file = File.open("data","rb") line = file.readline             # "Line 1.\r\n" puts "#{line.size} characters."  # 9 characters 二进制模式的结尾是一个回车换行对. file.close
binmode方法能够转换当前的流为二进制模式,这边要注意的是,一旦切换过去,就不能切换回来了:
Ruby代码
file = File.open("data")  
file.binmode  
line = file.readline             # "Line 1.\r\n"  
puts "#{line.size} characters."   # 9 characters  
file.close  

file = File.open("data") file.binmode line = file.readline             # "Line 1.\r\n" puts "#{line.size} characters."  # 9 characters file.close
如果你想使用更底层的输入输出,那你可以选择sysread和syswrite方法,他们接受一定数量的字节作为参数 .
Ruby代码
input = File.new("myfile",'a+')  
output = File.new("outfile",'a+')  
instr = input.sysread(10);  
puts instr  
bytes = output.syswrite("This is a test.")  

input = File.new("myfile",'a+') output = File.new("outfile",'a+') instr = input.sysread(10); puts instr bytes = output.syswrite("This is a test.")
如果文件指针已经到达文件的结尾时,sysread方法将会抛出一个异常.

这边要注意 Array 的pack和string的unpack方法,对于处理二进制数据非常有用.

分享到:
评论

相关推荐

    the ruby way

    3. **块、 Proc 和 Lambda**:Ruby中的块(blocks)、Proc对象和Lambda表达式是其强大的功能之一,它们允许程序员创建闭包和匿名函数,用于处理迭代和回调。 4. **元编程**:Ruby的元编程能力强大,允许在运行时...

    The ruby way

    - **简介**:`IO` 类是 Ruby 中所有 I/O 操作的基础,它定义了一系列用于输入和输出的基本方法。 - **核心方法**: - `IO.open`: 打开文件或设备。 - `IO#read`: 从打开的文件或设备读取数据。 - `IO#write`: 向...

    ruby实战书、代码书.rar

    6. **文件和IO操作**:Ruby提供了方便的文件和输入/输出操作,书里可能包含读写文件、流处理和系统交互等内容。 7. **测试驱动开发(TDD)**:Ruby与测试框架如RSpec和Minitest紧密集成,书中可能教导读者如何编写...

    Terminal-App-Start:终端机应用

    10. **学习资源**:想要学习如何用Ruby开发终端应用,可以参考Ruby官方文档,以及社区提供的教程、开源项目和gem,如“Learn Ruby the Hard Way”或“Ruby on Rails Tutorial”。 总结来说,“Terminal-App-Start”...

    sigar-sigar-1.6.4.tar.gz

    7 IO信息 包括IO的状态 读写大小等 8 服务状态信息 9 系统信息 包括操作系统版本 系统资源限制情况 系统运行时间以及负载 JAVA的版本信息等 ">开源工具包 SIGAR System Information Gatherer And Reporter 即 系统...

    wayback-machine-downloader:从Wayback Machine下载整个网站

    您需要在系统上安装Ruby(> = 1.9.2)-如果您还没有的话。 然后运行: gem install wayback_machine_downloader 提示:如果遇到权限错误,则可能必须在此命令前添加sudo 。 基本用法 使用您要检索的网站的基本URL...

    opennodes.arecord.us:打开Node.js用法概念!

    Open your way to Node.js 我们想搜集常使用的一些Node.js基本使用、观念、NPM套件等资讯于此,一则方便程式写作时查询使用,一则也给想要着手Node.js的人有机会可以了解使用Node.js。 Node.js是啥 Node.js对我来说...

Global site tag (gtag.js) - Google Analytics