你会如何关闭这个文件描述符?

时间:2015-10-23 04:31:13

标签: ruby

我们假设您有以下代码:

from_file, to_file = ARGV

puts "Copying from #{from_file} to #{to_file}"

#in_file = open(from_file)
#indata = in_file.read
indata = open(from_file).read # Combined in_file and indata.

puts "The input file is #{indata.length} bytes long."

puts "Does the output file exist? #{File.exist?(to_file)}"
puts "Ready, hit RETURN to continue or CTRL-C to abort."
$stdin.gets

out_file = open(to_file, 'w')
out_file.write(indata)

puts "Alright, all done."

out_file.close
#in_file.close

如何关闭indata调用的文件描述符?您需要关闭File open,但indata实际上是(File open).read

P.S。由于它是一个脚本,它将在退出时自动关闭。让我们假设我们正在运行一般的,始终如一的运行后端服务。而且我们不知道垃圾收集器是否会启动,因此我们需要明确关闭垃圾收集器。你会做什么?

2 个答案:

答案 0 :(得分:1)

Passing File.open a block通常是一种很好的方式,所以我会提供它作为替代方案,即使它似乎不是你所要求的。

indata = File.open(from_file) do |f|
    f.read
end

答案 1 :(得分:1)

如果您只是复制文件......

你可以使用FileUtils#cp

FileUtils.cp("from_file", "to_file")

甚至shell-out到操作系统并使用系统命令执行。

假设您想在将输入文件写入输出文件之前对输入文件执行某些操作。

如果from_file不大,......

您可以使用IO.read

将其“吞入”字符串中
str = IO.read(from_file)

根据需要操纵str,获取new_str,然后使用IO#write将其展开到输出文件:

IO.write("to_file", new_str)

请注意,对于课程File

File < IO #=> true # File inherits IO's methods

这就是为什么您经常会看到这样写的File.read(...)File.write(...)

如果from_file很大,请读一行,写一行......

如果要对每一行单独进行更改。

f = File.open("to_file", "w") # or File.new("to_file", "w")
IO.foreach("from_file") do |line|
  # < modify line to produce new_line >
  f.puts new_line
end
f.close
完成后,

foreach关闭"from_file"。如果f.close不存在,当包含代码的方法超出范围时,Ruby将关闭"to_file"。但是,如果在代码超出范围之前完成其他工作,最好关闭它。