Ruby - Get position Within a File

Introduction

When reading a file, you can get where you are within that file.

The pos method gives you access to this information:

Demo

f = File.open("main.rb") 
puts f.pos #   w  w w .ja va2 s. co m
puts f.gets 
puts f.pos

Result

Before you begin to read any text from the file, the position is shown as 0.

Once you've read a line of text, the position is moved.

pos returns the position of the file pointer.

The file pointer is the current location within the file that you're reading from.

It is the number of bytes from the start of the file.

pos can work both ways:

Demo

f = File.open("main.rb") 
f.pos = 8 # from  ww w .j ava  2  s .co m
puts f.gets 
puts f.pos

Result

Here, the file pointer was placed 8 bytes into the file before reading anything.

Related Topic