无法获取put来显示read()

时间:2013-06-09 19:56:00

标签: ruby

下面是我的代码似乎运行正常并按预期写入文件。但是,我只是不能得到第45行,放置target.read(),以显示目标的内容。请帮忙。哦,关于我的代码的其他部分的任何其他批评或建议也将非常感激。

filename = ARGV.first
script = $0

puts "We're going to erase #{filename}."
puts "If you don't want that, hit CTRL-C."
puts "If you do want that, hit RETURN."

print ">>"
STDIN.gets

puts "Opening the file...."
target = File.open(filename, 'w')

puts "Truncating the file."
target.truncate(target.size)

puts "Now, I'm going to ask for you three lines."

print "line 1: "; line1 = STDIN.gets.chomp()
print "line 2: "; line2 = STDIN.gets.chomp()
print "line 3: "; line3 = STDIN.gets.chomp()

puts "I'm going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
puts "Do you want to continue and perform the same"
puts "task with one line of target.write() methods?"
puts "Give me a 'yes' or a 'no'."
print ">>"
answer = STDIN.gets.chomp()
puts "=============================="
if answer == "yes"
target.write("#{line1}\n#{line2}\n#{line3}\n")
end

puts "This is the content of #{filename}:\n"
target = File.open(filename)
# Cannot figure out why the program is not displaying the contents
# of the target file when it's run.
puts target.read()
puts "And finally, we close it."
target.close()

2 个答案:

答案 0 :(得分:0)

您应该打开target进行阅读:

target = File.open(filename, 'r')

根据文档,read采用整数参数来表示要读取的字节数。而不是这个我建议使用迭代方法并逐个打印线。您之前也不必打开文件,但我想我会在开放时向您显示'r'参数。

这就是我要做的事情:

IO.foreach(filename) do |line|
  puts line
end

此方法在块完成后关闭文件,因此无需显式调用close。在阅读之前,请确保在写入文件后关闭该文件。

答案 1 :(得分:0)

尝试在'w +'mode中打开文件:

target = File.open(filename,'w+')

这样它就会打开文件读写,将现有文件截断为零长度 或创建一个新的文件进行阅读和写作。因此,不需要在代码中稍后显式截断。

完成写入后,文件光标位于文本末尾。在开始阅读之前,光标应该放回第一个字节:

target.rewind