PHP Ftruncate () Function

PHP

Syntax:
ftruncate (file, size) 
Parameters:The ftruncate() function in PHP takes two parameters .
  • file : This is a required parameter that specifies the file.
  • size : This is a required parameter that specifies new file size.
  • Returned value:Returns True on success and False on failure.Exceptions :
  • The rewind() function should be used after ftruncate() to replace the contents of a file.
  • The file pointer is not changed by ftruncate().
  • If the size specified in the parameter is larger than the file, then the file is expanded with zero bytes, and if the specified size is smaller than the file, then the file is truncated to this size
  • The programs below illustrate the ftruncate() function: Program 1 :
    // checking file size before truncating echo filesize ( "gfg.txt" );  
    // Open file $myfile = fopen ( "gfg.txt" , "a +" );  
    // truncate file ftruncate ( $myfile , 10);  
    // close the file fclose ( $file );  
    // Clear cache and check file size again
    clearstatcache(); echo filesize ( "gfg.txt" );  
    // close the file fclose ( $myfile ); ?>
    Output:
    500 10 
    Program 2 : $myfile = `gfg.txt` ;  
    // open file in read mode $myhandle = fopen ( $myfile , ` r + ` );  
    // truncate file ftruncate ( $myhandle , rand (1, filesize ( $myfile )));  
    // using reiwnd() to replace file content rewind ( $myhandle ); echo fread ( $myhandle , (< / code> $myfile ));  
    // close the file fclose ( $handle );  
    ?>
    Output:
    10 
    Link: http://php.net /manual/en/function.ftruncate.php



    Get Solution for free from DataCamp guru