从临时文件重写时出错

时间:2016-04-13 18:51:39

标签: ruby temporary-files

我正在从临时文件写入文件,当我尝试读取从临时文件中写入的文件时,似乎是在名为tmp的目录中添加了一个额外的字符。 (文件通过optparse传递)

来源:

require 'tempfile'

PATH = Dir.pwd

def format_file
  puts 'Writing to temporary file..'
  if File.exists?(OPTIONS[:file])
    file = Tempfile.new('file')
    IO.read(OPTIONS[:file]).each_line do |s|
      File.open(file, 'a+') { |format| format.puts(s) unless s.chomp.empty? }
    end
    IO.read(file).each_line do |file|
      File.open("#{PATH}/tmp/#sites.txt", 'a+') { |line| line.puts(file) }
    end
    puts "File: #{OPTIONS[:file]}, has been formatted and saved as #sites.txt in the tmp directory."
  else
    puts <<-_END_
                       Woah now my friend! I know you're eager to get those vulns;

                       But file: #{OPTIONS[:file]} doesn't exist or in this directory at least!

                       What I'm gonna need you to do is go move that file over here.
                       It's okay, you're forgiven, I'll wait until you return..
    _END_

  end
end

示例:

ruby whitewidow.rb -f sites.txt

[12:40:43 INFO]Formatting file
[12:40:43 INFO]Writing to temporary file..
[12:40:43 INFO]File: tmp/sites.txt, has been formatted and saved as #sites.txt in the tmp directory.
[12:40:43 INFO]Let's check out this file real quick like..
whitewidow.rb:224:in `read': No such file or directory @ rb_sysopen - C:/Users/Justin/MyScripts/RubySQL/whitewidow/#tmp/#sites.txt (Errno::ENOENT)
#<= Correct path but the '#' in tmp shouldn't be there..

它的作用是格式化文件以删除其中的任何空行(此程序不像空行)从那里写入临时文件,从临时文件重写回原始目录( whitewidow / tmp /)并删除临时文件(我知道如何做这部分)。

在我看来,当重写回原始目录时,它会在目录名称中添加##tmp实际上是tmp)是否有原因它添加了吗?

1 个答案:

答案 0 :(得分:0)

我修复了它,由于某种原因,该程序在路径中添加了#,因此我gsub删除了#并且它有效。