Simple IO question; full path not working

Hi guys. I'm running windows seven.

text2.txt is located in O:\Ruby

The program io.rb is located in O:\Ruby\Practice

io.rb contains the following code:

f = File.new("O:\Ruby\text2.txt", "r")
catch(:end_of_file) do
  loop do
    puts f.gets
    throw :end_of_file if f.eof?
  end
end
f.close

I run it in SciTE, got the following error:

ruby "io.rb"

io.rb:19:in `initialize': Invalid argument - O:Ruby ext2.txt
(Errno::EINVAL)
  from io.rb:19:in `new'
  from io.rb:19:in `<main>'

Exit code: 1

I fail to see anything wrong with the code. Can anyone help please?

If both io.rb and text2.txt are in O:\Ruby\Practice, and I change the
first line of code into: f = File.new("text2.txt", "r") ,
it works fine.

But I want to know why the full path isn't working if text2.txt is in a
different directory.

Thanks guys!!!!

···

--
Posted via http://www.ruby-forum.com/.

hi kaye -

  i don't have a windows 7 box to test on, but it looks like your
backslashes are disappearing when the `require` line is interpreted.

  you could try using single quotes instead of double, escaping the
backslashes, or using the File.join() method...

  hth,

  - j

···

--
Posted via http://www.ruby-forum.com/.

Kaye Ng wrote in post #1064561:

I fail to see anything wrong with the code. Can anyone help please?

Like jake already said: Don't use unescaped backslashes in double quoted
strings. The backslash is a special character.

Your string "O:\Ruby\text2.txt" is actually interpreted as

"O:Ruby ext2.txt"

Because the first backslash is discarded (there is no \R sequence). And
the \t is a tab.

I'd always use simple slashes in paths. This works on Windows, too:

'O:/Ruby/text2.txt'

···

--
Posted via http://www.ruby-forum.com/.

Kaye Ng wrote in post #1064561:

Hi guys. I'm running windows seven.

text2.txt is located in O:\Ruby

The program io.rb is located in O:\Ruby\Practice

io.rb contains the following code:

f = File.new("O:\Ruby\text2.txt", "r")

[...]

I fail to see anything wrong with the code. Can anyone help please?

When using double quotes with strings, use double backslashes, which
follows the way C strings work (characters after a single backslash are
escaped)

It is best to use normal slashes (forward slashes):

f = File.new("O:/Ruby/text2.txt", "r")

···

--
Luis Lavena

--
Posted via http://www.ruby-forum.com/.

Slightly off topic, but if you want an exception, couldn't you just use
f.readline? That automatically throws EOFError.

···

--
Posted via http://www.ruby-forum.com/.