轉載自http://hi.baidu.com/rubyonrailsjie/blog/item/28f683f319484314b17ec57c.html
1 打開和關閉一個文件
類方法File.new 打開一個文件,並將它實例化爲一個File對象,他的第一個參數是文件名.可選的第二個參數叫做 mode string(這個也是從c得來的).他的意思是怎樣打開一個文件(讀,寫或者其他的).默認是'r'(也就是讀).
- file1 = File.new("one") # Open for reading
- file2 = File.new("two", "w") # Open for writing
- file = File.new("three", 0755, File::CREAT|File::WRONLY)
出於對操作系統和運行環境的考慮,如果你打開了一個文件的話,你就必須關閉它。當你打開一個文件用於寫時,你更應該這樣做,從而才能免於丟失數據.close方法就是關閉一個文件:
- out = File.new("captains.log", "w")
- # Process as needed...
- out.close
這裏還有一個open方法,它的最簡單的形式是和new同義的:
- trans = File.open("transactions","w")
但是open方法還能夠帶一個block作爲參數,當存在block時,打開的文件將會做爲一個參數傳遞給block.這時這個文件將會在這個block的作用域裏,保持打開,直到block結束時,自動關閉:
- File.open("somefile","w") do |file|
- file.puts "Line 1"
- file.puts "Line 2"
- file.puts "Third and final line"
- end
2 更新文件
假設我們想要打開一個文件用於讀和寫,簡單的加一個'+'號到file mode就行了:
- 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就行了:
- 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):
- # myfile contains only: abcdefghi
- file = File.new("myfile")
- file.seek(5)
- str = file.gets # "fghi"
如果你能確定每一行都是固定的長度,你就能seek指定的行:
- # 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.
- 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.seek(-20, IO::SEEK_END) # twenty bytes from eof
- file.seek(20)
- pos1 = file.tell # 20
- file.seek(50, IO::SEEK_CUR)
- pos2 = file.pos # 70
5 操作二進制文件
在很久以前,c語言通過在file mode後附加一個'b'來表示將文件用二進制模式打開.在今天,二進制文件的處理已經沒有那麼麻煩了。在ruby中,一個字符串很容易保存一個二進制數據,而且也不用通過任何特殊的方式來讀文件.
可是在windows下是例外,在他下面,二進制文件和文本文件的不同是,在二進制mode下,結束行不能被轉義爲一個單獨的換行,而是被保存爲一個回車換行對.
另外的不同是,在文本模式下 control-Z被作爲文件的結束:
- # 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
再看下面的代碼:
- # 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
- file = File.open("data")
- file.binmode
- line = file.readline # "Line 1.\r\n"
- puts "#{line.size} characters." # 9 characters
- file.close
- input = File.new("myfile",'a+')
- output = File.new("outfile",'a+')
- instr = input.sysread(10);
- puts instr
- bytes = output.syswrite("This is a test.")
這邊要注意 Array 的pack和string的unpack方法,對於處理二進制數據非常有用.