Fastest way to get a byte at a position from a file?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Fastest way to get a byte at a position from a file?

Post by kaisellgren »

Hello,

I have data of over a megabyte. I need to get specific bytes from it (at specific positions). Eg position 165604. I was going to use arrays until I realized that PHP is imcapable of handling an array of 1024*1024 rows...

I need this to be as efficient as possible.

Do you got any ideas? My current idea is to read $pos bytes from the file then use substr($data,$pos,1)...
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Fastest way to get a byte at a position from a file?

Post by Mark Baker »

open the file, use fseek() to set your position, then read the data at that position

No need to read any additional data
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Re: Fastest way to get a byte at a position from a file?

Post by kaisellgren »

Mark Baker wrote:open the file, use fseek() to set your position, then read the data at that position

No need to read any additional data
Indeed, that's pretty fast 8)
User avatar
php_east
Forum Contributor
Posts: 453
Joined: Sun Feb 22, 2009 1:31 pm
Location: Far Far East.

Re: Fastest way to get a byte at a position from a file?

Post by php_east »

Code: Select all

$filename   = "myveryveryverylargefile.jpg";
$filesize   = filesize($filename);
$handle = fopen($filename, "r");
$contents = fread($handle, $filesize);
fclose($handle);
 
/* read 100 bytes, start at 165604 */
$span = 100;
$offset = 165604;
echo implode (' ',unpack ("@$offset/C$span", $contents));
 
die();
 
move backwards forwards and change window size as you wish by changing offset and span
( more at http://www.phpdig.net/ref/rn45re878.html )

p/s btw , absolutely no idea how this measures up with pos or seek, i'd be interested which is fastest. if you exclude file load time ( assuming you already have the data ), then i think this is fastest.
Post Reply