Basic problems with accessing a file

Hello,

I’m confused. I’m attempting to query a user for a filename to be
processed, and then I want to open that file for parsing. However, I’m
getting an error that the file does not exist. Hopefully someone can
help?

Here is my code:

Get filename

puts ("Please enter the name of the file you wish to process: ")
filename = gets
puts ("File to be processed: " + filename)
if File.exist?(filename)
puts “Exists.”
else
puts “Does not exist.”
end

Process file

File.open(filename, “r”) do |input_file|
while line = input_file.gets
puts line if line =~ /^[O] [/
end
end

Running this (Windows XP) produces the following:

C:\Documents and Settings\jcalivar\Desktop>ruby
RequirementsExtractor.rb
Please enter the name of the file you wish to extract requirements
from:
fred.txt
File to be processed: fred.txt
Does not exist.
RequirementsExtractor.rb:35:in `initialize’: No such file or directory

  • fred.txt (Errno::ENOENT)
    from RequirementsExtractor.rb:35:in `open’
    from RequirementsExtractor.rb:35

I can’t figure this out - because “fred.txt” certainly does exist on
my desktop. Help! :slight_smile:

James

Is the gets giving you a string with a \n on the end?

You might have to chomp it first.

“J” == James C. [email protected] writes:

J> puts ("Please enter the name of the file you wish to process: ")
J> filename = gets

filename = gets.chomp # to remove the newline which is at the end of
the
# string

J> puts ("File to be processed: " + filename)

Guy Decoux

I tried gets.chomp instead of gets and it worked! Thanks.

James