如何移动文件指针

时间:2013-04-16 13:27:45

标签: ruby

我需要在打开的文件中移动指针。我怎么能这样做?

File.open('example.txt', 'a+') do |f|
  f.move_pointer -1
  f.write 'end'
end

在我的示例中,我需要用文本替换最后一个字符

更新 我设法完成了任务,但看起来冗长无效:

File.open('example.txt', 'r+') do |f|
  contents = f.read[0...-1]
  f.rewind
  f.write contents + 'end'
end

1 个答案:

答案 0 :(得分:3)

尝试f.seek(-1, IO::SEEK_END)

(我在http://ruby-docs.com/docs/ruby_1.9.3/index.html上找到了这个)

修改

我能够以这种方式覆盖换行符终止文件的最后一个(非换行符)字符:

File.open('example.txt', 'r+') do |f|
  # go back 2 from the end, to overwrite 1 character and the final \n
  f.seek(-2, IO::SEEK_END)
  f.write("end\n")
end