0

I am facing a certain problem while trying to open files from a directory ( the directory is provided on the command line )

My code is as follows:

require 'optparse'
OptionParser.new do |opts|
   opts.banner = "Usage: rubyfile.rb [options]"

   options[:c] = ""
   opts.on( '-c', '--dir DILE', "Specify Directory with input files" ) do |e|
      options[:c] = e
   end

   options[:o] = ""
   opts.on( '-o', '--dir DILE', "Specify Output file" ) do |f|
      options[:c] = f
   end
end.parse!

out_file = File.open( options[:o], "a" )
dir_open = Dir.open( options[:c] )

Dir.foreach(dir_open) do | in_file |
   next if File.directory? in_file
   if( in_file.include? ".txt" )
      input_file = File.open( in_file, "r" )
      File.foreach(input_file).with_index do | line, line_s |
         puts line
      end
   end
end

If I try to print out the file names using puts in_file, it works. But when I try to open the file and dump out its contents, it does not.

I know I am missing something here not able to pinpoint what it is though.

  • I was able to get it done by saving the current path in a variable and then changing the directory of execution to dir_open using `Dir.chdir()`. Once I completed my processing, changed back to current path. I want to know if there is any other elegant way of handling this? – Lalit Motagi Jun 16 '16 at 15:20

1 Answers1

0

With this chunk right here:

  input_file = File.open( in_file, "r" )
  File.foreach(input_file).with_index do | line, line_s |
     puts line
  end

You could instead write File.readlines(in_file).each { |f| puts f }

File.readlines will return an array where each element is a line of the text.

max pleaner
  • 26,189
  • 9
  • 66
  • 118
  • still getting the same error. No such file or directory. I believe the path has to be included in some way when I want to open the file. Not able to figure out how. – Lalit Motagi Jun 15 '16 at 20:23
  • What is the value of `in_file` that is being passed to `File.readlines`? Is should be a string filepath. – max pleaner Jun 15 '16 at 20:29
  • in_file has only the filename. dir_open has the relative path. Do I have to do Dir.chdir() before trying to read the files? – Lalit Motagi Jun 15 '16 at 21:03
  • Using `readlines` can lead to problems. See http://stackoverflow.com/q/25189262/128421 Stick with `foreach` as it's an acceptable way to read a file. – the Tin Man Jun 15 '16 at 21:16