sabertooth has asked for the wisdom of the Perl Monks concerning the following question:

how can I open a file from the middle of the file rather than from the beginning of the file. I'm trying to avoid seek function. Can you help me out on this.
  • Comment on Initialsing file pointer in the middle of a file.

Replies are listed 'Best First'.
Re: Initialsing file pointer in the middle of a file.
by jethro (Monsignor) on Mar 15, 2010 at 13:27 UTC
    It seems you want seek without using seek. What exactly do you not like about the seek function?
      Actually I'm of the impression that seek function may eat up a lot of time if I'm suppose to execute it in a loop. I need to traverse a file and I may require constant vertical movement. But then performance is an issue here. I'm willing to initialise file pointers at the place where it is required. Is there a way to do that. Thanks for your reply.

        What gave you that impression?

        my $f; open($f,'<',"bigfile") or die "Could not open file\n"; my $i; while ($i++<1000000) { seek($f,10,0); seek($f,3000,0); }

        This script needs 1.2 seconds on my machine, for 2 millions seeks. Time for the loop without anything in it is 0.275 seconds, so we are at 460 nanoseconds per seek

        my $f; open($f,'<',"bigfile") or die "Could not open file\n"; my $i; my $g; while ($i++<1000000) { seek($f,10,0); $g= <$f>; seek($f,3000,0); } print length $g,"\n";

        This script additionally does one million reads of a 2 character string and runs 3 seconds. That means 1800 nanoseconds is the minimal time for a read (from cache obviously, if the data is on disk multiply that time by 1000 or more)

        Actually I'm of the impression that seek function may eat up a lot of time if I'm suppose to execute it in a loop.
        What makes you think that?
        I need to traverse a file and I may require constant vertical movement. But then performance is an issue here.
        Are you sure a file is actually your best option? Perhaps you are better off storing your data in a database. (But then, since your post doesn't say anything about the problem you are working on, it's just a pure guess).
        I'm willing to initialise file pointers at the place where it is required. Is there a way to do that. Thanks for your reply.
        A file pointer is just some structure holding some information. One field of that structure is the "offset". Reading or writing updates the offset. So does a seek.
        seek is used to move the file pointer, there is no other function for doing that