ftruncate 


php128 apg

TRUNCATES a file to a given length.





If $size is larger than the file then the file is extended with null bytes.

If $size is smaller than the file then the file is truncated to that $size.

This function upon success, returns TRUE, otherwise, returns FALSE.



<?php

bool ftruncate 
res $stream int $size )


where,

$stream A file system pointer

$size 
The size to truncate to

?>

 $stream 


A file system pointer typically created by fopen.



  $size   


The size to truncate to.



  1 EXERCISE   

<?php

$dir01 
__DIR__ '/temp/';

$file01a 'blahblahblah.txt';

$file01b $dir01 $file01a;

$fp01 fopen($file01b'r');

$len01 filesize($file01b);

$rnd01 mt_rand(1$len01);

ftruncate($fp01$rnd01);

rewind($fp01);

echo 
fread($fp01$len01);

fclose($fp01);

?>

  2 EXERCISE   

<?php

/* 

  Run this exercise several times
  For each new run a new result will be obtained
  
  This function may be difficult to display 
  for accented characters in the last position

*/

$dir02 __DIR__ '/temp/';

$file02a 'blahblahblah.txt';

$file02b $dir02 $file02a;

$fp02 fopen($file02b'r');

rewind($fp02);

$len02 mt_rand(1200);

ftruncate($fp02$len02);

rewind($fp02);

$fread02 fread($fp02$len02);

echo 
$fread02 "<br><br>";

var_dump($fp02);

echo 
"<br><br>" $len02 ' characters read.';

fclose($fp02);

?>