1

I have a problem with my program. It says: "`write': closed stream (IOError)".

def backup(dir, file, time="")
    fullpath = "#{dir}/#{file}"
    #puts fullpath

        @f.puts "BKP_DATE: #{$date}"
        @f.puts "BKP_DIRECTORY: #{dir}"
        @f.puts "M_TIME: #{time}"
        @f.puts "BKP_FILE: #{file}"


        IO.readlines(fullpath).each do |line|

            @f.puts line
        end
        @f.close()

end
sawa
  • 165,429
  • 45
  • 277
  • 381
Quentin
  • 75
  • 1
  • 2
  • 11
  • What's the question here? – Sergio Tulentsev Feb 07 '14 at 10:34
  • Maybe you are calling `backup` two times in a row without reopening the file `@f`? – toro2k Feb 07 '14 at 10:44
  • In my program i've call two times the function backup. if self.backup(base, f, temps) != false puts self.backup(base, f, temps) end He is call in the if and the puts. Works well if i comment the if... Can we pause Ruby Script ? (5 seconds for exemple). Thanks you for your answer. – Quentin Feb 07 '14 at 11:06

1 Answers1

4

So your program is essentially like this:

f = File.open("foo.dat", "w")

f.puts "BKP_DATE: "
...
IO.readlines(fullpath).each do |line|
    f.puts line
end
f.close
f.puts "BKP_DATE: "
...
IO.readlines(fullpath).each do |line|
    f.puts line
end
f.close

You tried to close the same File object twice.

I don't know the whole structure of your program, but perhaps you should instantiate the File object inside your backup method. And this is how you should write it in Ruby (:

File.open("foo.dat", "w") {|f|
    f.puts "BKP_DATE: "
    IO.readlines(fullpath).each do |line|
        f.puts line
    end
} # f is automatically closed here

If you really need to open the file outside your backup method, I think what you need at the end of bakcup is @f.flush rather than @f.close. This would be an acceptable solution for you provided that you don't open hundreds of files in your script.

As for pausing, try sleep 5.0

nodakai
  • 7,773
  • 3
  • 30
  • 60