On Sunday 09 June 2002 02:07 pm, Kurt Euler wrote:
> Thanks a lot, Park and Sean.
>
> Two questions:
>
> - Sean, what do you mean by CG when you write in your message "This
> is exactly the type of error that CG causes"?

I believe he meant GC, as in garbage collection. There is nothing about 
intrinsic about garbage collection that causes too many open files. =) 
Perhaps he meant that with a language that has garbage collection, it's 
a lot easier to write code that leaves files open and never closes 
them? I won't put words in his mouth, but that may have been what he 
was referring to.

> - Is there a set limit on the number of files that can be open? If
> so, how many?

It depends on the operating system and various process limits that may 
be set. The limits I've seen on various systems range from tens to 
thousands. Usually having more than a handful of files open at a time 
means trouble.

> - Park, you write that one option is this:
>
>        inserta = File.new("./input/intro_subtemplate.txt").read
>
>        should be
>
>        f = File.new("./input/intro_subtemplate.txt")
>        inserta = f.read
>        f.close

The first one creates a file object, does a read, then the file object 
is floating. If and when it gets garbage collected, the file will be 
closed. But if you run a ton of these commands in a row, it's extremely 
easy to open more files than is allowed by the OS before the garbage 
collector ever kicks in. (Perhaps ruby ought to catch the error and run 
the garbage collector, then try again transparently?)

The second one closes the file explicitly, and thus can never have the 
problem the first one does. But it requires an extra variable and you 
have to remember to close it.

I usually use something like this instead:

inserta = ''   # assuming inserta isn't already a local variable
File.open("./input/into_subtemplate.txt") { |f| inserta = f.read }

Since a block is passed to File.open, the file is automatically closed 
after the block is executed. Not so with the first example you typed 
above. =)

-- 
Wesley J. Landaker - wjl / icecavern.net
OpenPGP FP: C99E DF40 54F6 B625 FD48  B509 A3DE 8D79 541F F830