Forum: Ruby Question concerning ruby file access

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8e16f7669af5b4ecfa4f2b89f32b21b6?d=identicon&s=25 Stefan Salewski (Guest)
on 2008-10-30 01:15
(Received via mailing list)
Question concerning ruby file access from a novice:

I have seen following code fragment from

http://www.rubycentral.com/pickaxe/tut_io.html

File.open("testfile", "r") do |aFile|
# ... process the file
end

Advantage of this notation is that file is automatically closed when do
loop terminates -- maybe by an exception with Process.exit.

But how do I test in this notation that the file with name "testfile"
really exits (and opening was successful). In an multi-tasking
environment another process may delete the file just before this
statement is executed.

Or in other words: I want to print a text like "File with filename
"testfile" does not exist" when opening failed.

Best regards

Stefan Salewski
7a561ec0875fcbbe3066ea8fe288ec77?d=identicon&s=25 Sebastian Hungerecker (Guest)
on 2008-10-30 01:26
(Received via mailing list)
Stefan Salewski wrote:
> But how do I test in this notation that the file with name "testfile"
> really exits (and opening was successful). In an multi-tasking
> environment another process may delete the file just before this
> statement is executed.

If you want to completely avoid race conditions, you don't check - you
just do
and then recover from eventual errors (i.e. you rescue the exception).

HTH,
Sebastian
6087a044557d6b59ab52e7dd20f94da8?d=identicon&s=25 Peña, Botp (Guest)
on 2008-10-30 02:35
(Received via mailing list)
From: Stefan Salewski [mailto:mail@ssalewski.de]
# Or in other words: I want to print a text like "File
# with filename "testfile" does not exist" when opening failed.

i usually think it like db's logical unit of work or transaction. i just
wrap it w ruby's begin/end and a rescue check as mentioned by sebastian.

something like eg

> begin
* File.open("test.rbx") do |f|
* end
> rescue =>e
>   p e.message
> end
"No such file or directory - test.rbx"
=> nil

note, you can have more rescues and finetune them. you can also make
your own exceptions.. just continue reading on the pickaxe..
851acbab08553d1f7aa3eecad17f6aa9?d=identicon&s=25 Ken Bloom (Guest)
on 2008-10-30 02:40
(Received via mailing list)
On Thu, 30 Oct 2008 00:14:57 +0000, Stefan Salewski wrote:

> loop terminates -- maybe by an exception with Process.exit.
>
> Stefan Salewski

begin
  File.open("testfile") do |aFile|
    ...
  end
rescue IOError => e
  #handle error
end
This topic is locked and can not be replied to.