6.19 Truncating a File


You want to chop off the last line of a file.

Technique

Use the ftruncate() function along with the ftell () function:

 <?php $fp = @fopen ($fn, "r+")   or die ("Cannot open $fn"); while (true) {     $last_addr = $addr;     $addr = ftell ($fp);     if (!@fgets ($fp, 1024))         break; } ftruncate ($fp, $last_addr); fclose ($fp)   or die ("Cannot close $fn"); ?> 

Comments

In this recipe we read the file line-by-line , remembering $addr (address of the current line) and $last_addr (address of the previous line). Finally, when we reach the end of the file, we use the ftruncate() function to remove the last line of the file.

Loading the file into an array, removing the last line of the file, and then writing the data back to your file can also obtain this effect (less effectively):

 <? $f_contents = file ($fn); array_pop ($f_contents); $fp = fopen ($fn, "w")   or die("Cannot open file $fn"); fwrite ($fp, implode ('', $f_contents)); @fclose ($fp)   or die("Cannot close file $fn"); ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net