Basic problems with accessing a file

J

James Calivar

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! :)

James
 
T

ts

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)
 
P

Peter Hickman

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

You might have to chomp it first.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top