首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法获取puts以显示read()

无法获取puts以显示read()
EN

Stack Overflow用户
提问于 2013-06-10 03:56:00
回答 2查看 97关注 0票数 2

下面是我的代码,它看起来运行得很好,并按照预期写入文件。但是,我就是不能让第45行放入target.read()来显示目标的内容。请帮帮忙。哦,关于我的代码的其他部分的任何其他批评或建议也将非常感谢。

代码语言:javascript
复制
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()
EN

回答 2

Stack Overflow用户

发布于 2013-06-10 04:05:11

您应该打开target进行阅读,如下所示:

代码语言:javascript
复制
target = File.open(filename, 'r')

根据文档,read接受一个整数参数来表示要读取的字节数。取而代之的是,我建议使用迭代方法并逐行打印。你以前也不必打开这个文件,但我想我还是在open中给你看一下'r‘参数吧。

这就是我要做的:

代码语言:javascript
复制
IO.foreach(filename) do |line|
  puts line
end

此方法在块完成后关闭文件,因此不需要显式调用close。在读取之前,请确保在写入文件后将其关闭。

票数 0
EN

Stack Overflow用户

发布于 2013-06-10 04:35:35

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

代码语言:javascript
复制
target = File.open(filename,'w+')

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

当您完成编写时,文件光标位于文本的末尾。在开始读取之前,应将光标放回第一个字节上:

代码语言:javascript
复制
target.rewind
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17013588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档