downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

fwrite> <ftell
[edit] Last updated: Wed, 22 May 2013

view this page in

ftruncate

(PHP 4, PHP 5)

ftruncateTrunca un archivo a una longitud dada

Descripción

bool ftruncate ( resource $handle , int $size )

Toma el puntero al archivo, handle, y trunca el archivo a la longitud size.

Parámetros

handle

El puntero al archivo.

Nota:

handle puede ser abierto para escritura.

size

El tamaño a truncar.

Nota:

Si size es mayor que el del archivo, éste se extiende con bytes null.

Si size es menor que el del archivo, éste será truncado a ese tamaño.

Valores devueltos

Devuelve TRUE en caso de éxito o FALSE en caso de error.

Historial de cambios

Versión Descripción
4.3.3 Antes de esta versión ftruncate() devolvía un valor integer de 1 si tenía éxito, en vez del boolean TRUE.

Ejemplos

Ejemplo #1 Ejemplo de truncar un archivo

<?php
$nombre_archivo 
'lorem_ipsum.txt';

$gestor fopen($nombre_archivo'r+');
ftruncate($gestorrand(1filesize($nombre_archivo)));
rewind($gestor);
echo 
fread($gestorfilesize($nombre_archivo));
fclose($gestor);
?>

Notas

Nota:

El puntero al archivo no es cambiado.

Ver también

  • fopen() - Abre un fichero o una URL
  • fseek() - Busca sobre un puntero a un fichero



fwrite> <ftell
[edit] Last updated: Wed, 22 May 2013
 
add a note add a note User Contributed Notes ftruncate - [5 notes]
up
1
rc at opelgt dot org
5 years ago
Writing after ftruncate

I didnt expect that I can write in the middle of nowhere. I thought that I would write at the beginning of the file but the first 4 bytes were filled automatically with NULLs followed by "56":

<?php
$str1 
= 1234;
$str2  =   56;
$datei = "test.txt";

$dh = fopen($datei,"w");
fwrite($dh, $str1);
fclose($dh);

$dh = fopen ($datei,"r+");
echo
"content: ".fread($dh, filesize($datei))."<br>";
echo
"pointer after fread at: ".ftell($dh)."<br>";
ftruncate($dh, 0);
echo
"pointer after truncate at: ".ftell($dh)."<br>";
fwrite($dh, $str2);
echo
"pointer after fwrite at: ".ftell($dh)."<br>";
rewind($dh);
echo
"pointer after rewind at: ".ftell($dh)."<br>";
$str = fread($dh, 6);
echo
"content: $str<br>in ASCII: ";
for(
$i = 0; $i < 6; $i++)
 echo
ord($str{$i})."-";
fclose($dh);

/*
   OUTPUT:
   content: 1234
   pointer after fread at: 4
   pointer after truncate at: 4
   pointer after fwrite at: 6
   pointer after rewind at: 0
   content: 56
   in ASCII: 0-0-0-0-53-54
*/
?>

So not only ftruncate is filling an empty file up with NULLs as in the note before. Fread is filling leading space with NULLs too.
up
-1
yetihehe at yetihehe dot com
3 years ago
Simple script which will delete spaces from end of php files (suitable in big sites, when you are including many files before sending headers and without output buffering):

<?php
function mapfiles($func,$filename,$level=0) {
  if(
is_dir($filename)) {
    if(
$level>30) return; //limit recurence in case of looped dirs
   
$handle=opendir($filename);
    while((
$dirname=readdir($handle))!==false) {
      if(
$dirname=='.'||$dirname=='..') continue;
     
mapfiles($func,$filename.'/'.$dirname,$level+1);
    }
   
closedir($handle);
  } else {
   
$func($filename);
  }
}

function
scanfile($filename) {
  if(
substr($filename,-4)!=".php") return;
 
$ff=fopen($filename,"r+");
 
fseek($ff, -10, SEEK_END);
 
$str=fread($ff,12);
 
$matches=array();
  if(
preg_match('/\?>(\s+)$/',$str,$matches)) {
   
$fsize=filesize($filename);
   
ftruncate($ff, $fsize-strlen($matches[1]));
  }
 
fclose($ff);
}

mapfiles("scanfile",".");
?>
up
0
emailfire at gmail dot com
1 year ago
If you want to empty a file of it's contents bare in mind that opening a file in w mode truncates the file automatically, so instead of doing...

<?php
$fp
= fopen("/tmp/file.txt", "r+");
ftruncate($fp, 0);
fclose($fp);
?>

You can just do...

<?php
$fp
= fopen("/tmp/file.txt", "w");
fclose($fp);
?>
up
0
eurosat7 at yahoo dot de
2 years ago
If you want to ftruncate but keep the end:
<?php
   
function ftruncatestart($filename,$maxfilesize){
       
$size=filesize($filename);
        if (
$size<$maxfilesize*1.0) return;
       
$maxfilesize=$maxfilesize*0.5; //we don't want to do it too often...
       
$fh=fopen($filename,"r+");
       
$start=ftell($fh);
       
fseek($fh,-$maxfilesize,SEEK_END);
       
$drop=fgets($fh);
       
$offset=ftell($fh);
        for (
$x=0;$x<$maxfilesize;$x++){
           
fseek($fh,$x+$offset);
           
$c=fgetc($fh);
           
fseek($fh,$x);
           
fwrite($fh,$c);
        }
       
ftruncate($fh,$maxfilesize-strlen($drop));
       
fclose($fh);
    }
?>
It will not just cut it but search for a newline so you avoid corrupting your csv or logfiles. But I don't know if you will stress the reading head of your drive. ;)
up
-2
mike at mikeleigh dot com
6 years ago
I have produced a number of tests below which walk through my findings of the ftruncate function.  For the impatient among you ftruncate can be used to increase the size of the file and will fill the rest of the file with CHR 0 or ASCII NULL.  It can be used as a very convenient way of making a 1Mb file for instance.

Test 1
<?php
/*
  Test 1: Write "some text" to a file.
  Result: The text "some text" should be present in test_1.txt
*/
$fp = fopen('test_1.txt', 'w+');
fwrite($fp, 'some text');
?>
The first test is only here to make sure that a file can be written with some text.

Test 2
<?php
/*
  Test 2: Write "some text" to a file and ftruncate the file to 4 bytes.
  Result: The text "some" should be present in test_2.txt as the file will have been truncated to 4 bytes.
*/
$fp = fopen('test_2.txt', 'w+');
fwrite($fp, 'some text');
ftruncate($fp, 4);
?>
As expected the file has been truncated to 4 bytes.

Test 3
<?php
/*
  Test 3: Write "some text" to a file and ftruncate the file to 40 bytes.
  Result: The text "some text" should be present in test_3.txt as the file will have been truncated to 40 bytes.
*/
$fp = fopen('test_3.txt', 'w+');
fwrite($fp, 'some text');
ftruncate($fp, 40);
?>
Interestingly the file has increased from 9 bytes to 40 bytes.  The remaining 31 bytes of the file are ASCII code 0 or NULL though.

Further notes can be found here http://mikeleigh.com/links/ftruncate

 
show source | credits | sitemap | contact | advertising | mirror sites