2010-07-05 19 views
1

我正在計算模塊失敗進入文件的次數。所以無論何時失敗,我打開文件,增加文件中的數字並關閉它。我該如何做到這一點,打開文件只是一次,而不是打開它兩次閱讀和另一個寫作。如何在紅寶石中增加寫入文件的計數器

感謝

回答

4

假定爲腳本調用,從在同一目錄counter.txt命名的文件。該文件除了數字之外應該沒有任何其他內容。

File.open 'counter.txt' , 'r+' do |file| 
    num = file.gets.to_i 
    file.rewind 
    file.puts num.next 
end 

基本上,當它完成它opens the file「counter.txt」的reading and writing starting at the beginning of the file它使用的,以確保該文件打開塊形式被關閉。它gets the number然後converts it to an integer獲得當前計數。它rewinds the file pointer,以便它再次在文件的開始(因爲我們想寫在舊號碼)然後prints out to the file增加的數字。

+0

第一次。如果我想創建一個文件並在其中寫入0。它正在拋出一個異常,因爲我們正在用r +模式打開。如何處理這種情況? – anusuya 2010-07-05 09:25:49

+0

'$ touch counter.txt' – 2010-07-05 10:18:57

+0

有沒有辦法通過鎖定文件來做到這一點,所以它會工作,如果多個進程正在運行腳本? – 2015-12-09 02:45:41