加载中...

习题 16: 读写档案


如果你做了上一个练习的加分习题,你应该已经了解了个个种文件相关的命令(方法/函式)。你应该记住的命令如下:

  • close – 关闭档案。跟你编辑器的 文件->儲存.. 是一样的意思。
  • read – 读取档案内容。你可以把结果赋给一个变量。
  • readline – 读取档案文字中的一行。
  • truncate – 清空文件,请小心使用该命令。
  • write(stuff) – 将 stuff 写入档案。

这是你现在应该知道的重要命令。有些命令需要接收参数,但这对我们并不重要。你只要记住 write 的用法就可以了。 write 需要接收一个字串作为参数,从而将该字串写入档案。

让我们来使用这些命令做一个简单的文字编辑器吧:

  1. filename = ARGV.first
  2. script = $0
  3. puts "We're going to erase #{filename}."
  4. puts "If you don't want that, hit CTRL-C (^C)."
  5. puts "If you do want that, hit RETURN."
  6. print "? "
  7. STDIN.gets
  8. puts "Opening the file..."
  9. target = File.open(filename, 'w')
  10. puts "Truncating the file. Goodbye!"
  11. target.truncate(target.size)
  12. puts "Now I'm going to ask you for three lines."
  13. print "line 1: "; line1 = STDIN.gets.chomp()
  14. print "line 2: "; line2 = STDIN.gets.chomp()
  15. print "line 3: "; line3 = STDIN.gets.chomp()
  16. puts "I'm going to write these to the file."
  17. target.write(line1)
  18. target.write("\n")
  19. target.write(line2)
  20. target.write("\n")
  21. target.write(line3)
  22. target.write("\n")
  23. puts "And finally, we close it."
  24. target.close()

这是一个大档案,大概是你键入过的最大的档案。所以慢慢来,仔细检查,让它能够跑起来。有一个小技巧就是你可以让你的脚本一部分一部分地跑起来。先写 1-8 行,让它能跑起来,再多做 5 行,再接着几行,以此类推,直到整个脚本都可以跑起来为止。

你应该看到的结果

你将看到两样东西,一样是你新脚本的输出:

  1. $ ruby ex16.rb test.txt
  2. We're going to erase 'test.txt'.
  3. If you don't want that, hit CTRL-C (^C).
  4. If you do want that, hit RETURN.
  5. ?
  6. Opening the file...
  7. Truncating the file. Goodbye!
  8. Now I'm going to ask you for three lines.
  9. line 1: To all the people out there.
  10. line 2: I say I don't like my hair.
  11. line 3: I need to shave it off.
  12. I'm going to write these to the file.
  13. And finally, we close it.
  14. $

这是一个大档案,大概是你键入过的最大的档案。所以慢慢来,仔细检查,让它能够跑起来。有一个小技巧就是你可以让你的脚本一部分一部分地跑起来。先写 1-8 行,让它能跑起来,再多做 5 行,再接着几行,以此类推,直到整个脚本都可以跑起来为止。

加分习题

  1. 如果你觉得自己没有弄懂的话,用我们的老方法,在每一行之前加上注释,为自己理清思路。就算不能理清思路,你也可以知道自己究竟具体哪里没弄清楚。
  2. 写一个和上一个习题类似的脚本,使用 read 和 ARGV 读取你刚才新建立的文件。
  3. 档案中重复的地方太多了。试着用一个 target.write() 将 line1 , line2 , line3 印出来,你可以使用字串、格式化字串以及跳脱字串。
  4. 找出为什么我们打开档案时要使用 w 模式,而你真的需要 target.truncate() 吗?去看 Ruby 的 File.open 函式找答案吧。

还没有评论.