To move the pointer forward by a certain offset or move the pointer to a certain position backward from the end of the file, you need to use seek.
seek has three modes of operation:
Mode | Description |
---|---|
IO::SEEK_CUR | Seeks a certain number of bytes ahead of the current position. |
IO::SEEK_END | Seeks to a position based on the end of the file. This means that to seek to a certain position from the end of the file. |
IO::SEEK_SET | Seeks to an absolute position in the file. This is identical to pos=. |
To position the file pointer 5 bytes from the end of the file and change the character to an X , you would use seek as follows:
f = File.new("test.txt", "r+") f.seek(-5, IO::SEEK_END) # from w w w . ja va2s.com f.putc "X" f.close
The following code prints every fifth character in a file:
f = File.new("test.txt", "r") while a = f.getc puts a.chr # from w w w . j a v a 2s . c om f.seek(5, IO::SEEK_CUR) end