leemour
leemour

Reputation: 12013

How to move file pointer

I need to move a pointer in an open file. How can I do something like this?

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

In my example I need to replace the last character with my text

Update I managed to complete the task but it looks verbose and ineffective:

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

Upvotes: 2

Views: 3782

Answers (1)

Wally Altman
Wally Altman

Reputation: 3545

Try f.seek(-1, IO::SEEK_END).

(I found this on http://ruby-docs.com/docs/ruby_1.9.3/index.html)

Edit

I was able to overwrite the last (non-linebreak) character of a newline-terminated file this way:

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

Upvotes: 3

Related Questions