Skip to content
Related Articles
Open in App
Not now

Related Articles

PHP | ftruncate( ) Function

Improve Article
Save Article
  • Last Updated : 19 Jun, 2018
Improve Article
Save Article

The ftruncate() function in PHP is an inbuilt function which is used to truncate(shorten) an open file to the specified length. The file and the new size of the file are sent as parameters to the ftruncate() function and it returns True on success and False on Failure. If size specified in the parameter is larger than the file then the file is extended with null bytes and if size specified is smaller than the file then the file is truncated to that size.

Syntax :

ftruncate(file, size)

Parameters: The ftruncate() function in PHP accepts two parameters.

  1. file: It is a mandatory parameter which specifies the file.
  2. size : It is a mandatory parameter which specifies the new size of the file.

Return Value: It returns True on success and False on Failure.

Exceptions:

  1. rewind() function must be used after ftruncate() function to replace file content.
  2. The file pointer is not changed by the ftruncate() function.
  3. If size specified in the parameter is larger than the file then the file is extended with null bytes and if size specified is smaller than the file then the file is truncated to that size

Below programs illustrate the ftruncate() function:

Program 1:




<?php
// checking filesize before truncating
echo filesize("gfg.txt");
  
// Opening the file
$myfile = fopen("gfg.txt", "a+");
  
// truncating the file
ftruncate($myfile, 10);
  
// closing the file
fclose($file);
  
// Clearing cache and checking filesize again
clearstatcache();
echo filesize("gfg.txt");
  
// closing the file
fclose($myfile);
?>


Output:

500
10

Program 2:




<?php
$myfile = 'gfg.txt';
  
// opening file in read mode
$myhandle = fopen($myfile, 'r+');
  
// truncating the file
ftruncate($myhandle, rand(1, filesize($myfile)));
  
// using reiwnd() to replace file content
rewind($myhandle);
echo fread($myhandle, filesize($myfile));
  
// closing the file
fclose($handle);
  
?>


Output:

10

Reference : http://php.net/manual/en/function.ftruncate.php


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!