FilePointer

The file-pointer is like the needle on a old vinyl gramophone. You can lift the arm and reposition the needle anywhere on the LP (or EP).

In Ruby you use seek and tell from IO.

fh = File.open('file.txt')
fh.seek(0, :END) # move pointer to end
EOF = fh.tell # read pointer value
fh.seek(0, :SET) # move pointer to beginning

Any reading from the file starts from where the file-pointer is.

fh.seek(-200, :CUR)
p fh.readline

I used this to make an indexer. It reads tags in the file and stores the file-pointer position in a corresponding yaml-file.

---
top: 8
contents: 1774
chapter_01: 2582
chapter_02: 25425
chapter_03: 55372
chapter_04: 76444
chapter_05: 97586
chapter_06: 125878
chapter_07: 141895
chapter_08: 161387
chapter_09: 182444
chapter_10: 202398
chapter_11: 224402
chapter_12: 249889

Taking command-line arguments --tag and --lines, I can position the pointer and start reading the number of lines without having to go through the entire file.

x_show --tag chapter_08 --lines 20

Problem: The yaml-file must be updated to be ‘in sync’ with the file. How to resolve this?

  1. Move the pointer. Read the line(s).. and check one line up.. if the tag is there.
  2. better: check file creation time. If the yaml-file is not older than the file it is supposed to index.. something is not right.