tags:

views:

47

answers:

1

I am making a count of how many times a module fails into a file. so whenever it fails, i open the file, increment the number in the file and close it. How i can i do it with opening the file just once instead of opening it twice once for reading and another of writing.

Thanks

+3  A: 

Assumes a file named counter.txt in the same dir as the script is invoked from. The file should have nothing other than the number in it.

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

Basically, it opens the file 'counter.txt' for reading and writing starting at the beginning of the file It uses the block form of open in order to ensure the file is closed when it is done. It gets the number and then converts it to an integer to get the current count. It rewinds the file pointer so that it is at the beginning of the file again (because we want to write over the old number) Then prints out to the file the incremented number.

Joshua Cheek
for the first time. if i want to create a file and write 0 in it. it is throwing an exception as we are opening with r+ mode. how to handle this situation?
railscoder
`$ touch counter.txt`
Joshua Cheek