From: Jos Backus Date: 2004-12-06T15:57:38+09:00 Subject: Re: Obtaining mode information on a File object On Sun, Dec 05, 2004 at 11:32:36PM +0900, Robert Klemme wrote: > > "Jos Backus" schrieb im Newsbeitrag > news:20041204195115.GA83981@lizzy.catnook.com... > >Another question... How do I access the File open mode ("w" in this case) > >on a > >File object? Example: > > > >class Foo > > def initialize(file) > > begin > > yield self > > ensure > > # We only want to call finalize when the file was opened for writing; > > # The following doesn't work, but how _do_ you do this? > > finalize(file) if file.mode.writable? # file was opened with mode "w" > > end > > end > > def finalize(file) > > file.puts "END" > > end > >end > > > >File.open("foo", "w") do |file| > > a = Foo.new(file) do > > # ... Use a ... > > end > >end > > First of all, I know no other way than to just try to write to the file and > see what happens. Maybe writing an empty string is a solution on some > (all?) platforms. I hadn't thought of that. It seems... wrong. This information is available already, it's a matter of making it accessible using an attribute reader. > But I think usually you don't need that info: if a method requires an IO > object open for writing then it simply uses it that way and you get bitten > by an exception if it's not open for writing. Similar applies for files > needed for reading. > > What is the scenario where you need that? I'm writing a class to handle CPIO archives. Iff the file passed in was opened for writing I want to call a finalizer that appends a trailer, as in the above code snippet. I'm currently looking at io.c to see if the vmode variable in rb_open_file can't be exported somehow, like filename. One issue is that the mode argument can be either a String or Fixnum (things like O_RDONLY), which complicates matters. Thanks, -- Jos Backus _/ _/_/_/ Sunnyvale, CA _/ _/ _/ _/ _/_/_/ _/ _/ _/ _/ jos at catnook.com _/_/ _/_/_/ require 'std/disclaimer'