Perl seek function -


this problem solved. thank much.
question , solution using stated below.

question:

open in, "<./test.txt"; seek(in,10,0); read in, $temp, 5;  seek(in,20,0); close(in); 


situation that, handle start @ position 0.
after first seek function, file handle @ position 10.
after read, handle @ position 15.
@ moment, seek again. program seek beginning or position 20.
question is there anyway me searching in file not need search starting point of file every time?


the way using:

use fcntl qw(seek_set seek_cur seek_end); #seek_set=0 seek_cur=1 ...  $target_byte=30; open in, "<./test.txt"; seek(in,10,seek_set); read in, $temp, 5;  $position=tell(in); seek(in,$target_byte-$position,seek_cur); #do want close(in); 

before start,

  • the assumption ask make no sense. first byte @ position zero. always.

  • it's called "file handle" (since allows hold onto file), not "file handler" (since doesn't handle anything).

it clearer if used constants seek_set, seek_cur , seek_end instead of 0, 1 , 2.

your code then

use fcntl qw( seek_set );  open in, "<./test.txt"; seek(in,10,seek_set); read in, $temp, 5;  seek(in,20,seek_set); close(in); 

as name implies, sets position specified value.

so,

  • after first seek, file position 10.
  • after read, file position 15.
  • after second seek, file position 20.

visually,

         +--------------------------  0: initially.          |         +---------------- 10: after seek($fh, 10, seek_set).          |         |    +----------- 15: after reading "klmno".          |         |    |    +------ 20: after seek($fh, 20, seek_set).          |         |    |    |          v         v    v    v      file:    abcdefghijklmnopqrstuvwxyz indexes: 01234567890123456789012345 

if wanted seek relative current position, you'd use seek_cur.

         +--------------------------  0: initially.          |         +---------------- 10: after seek($fh, 10, seek_cur).          |         |    +----------- 15: after reading "klmno".          |         |    |         +- 25: after seek($fh, 10, seek_cur).          |         |    |         |          v         v    v         v  file:    abcdefghijklmnopqrstuvwxyz indexes: 01234567890123456789012345 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

keyboard - C++ GetAsyncKeyState alternative -

android - java.net.UnknownHostException(Unable to resolve host “URL”: No address associated with hostname) -