2006/6/6, Dirk Meijer <hawkman.gelooft / gmail.com>:
> hello list!
> i've learnt to open files like this:
>
> File.open("foo", "w") do |file|
>   file.write "foo"
> end
>
> because everyone always says it's _dangerous_ to leave files open...
> just, wondering, what could really happen?
>
> suppose i write a program that write to a file, infinitely, i'll want to
> shut this program off after a while, the file will not properly close...
> what could actually happen?

With buffering IO your changes might not be written to the file (this
might depend on OS and the way your process terminates).  Also, if you
open the same file multiple times from the same process you might also
see weird effects.  Lastly, keeping a file descriptor open for longer
than needed may cause you troubles if you open many files, because
tehre is a limit on the max number of open file descriptors.

Note that in your scenario you can alternatively do the closing in
at_exit or END block depending on how you architect your software.  If
the sole task of the software is to write to a single file then I'd
probably still rather use the block approach and have your main
program inside that block.

Kind regards

robert


-- 
Have a look: http://www.flickr.com/photos/fussel-foto/