PHP | ftruncate( ) Function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
?>

chevron_right


Output:

500
10

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
  
?>

chevron_right


Output:

10

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



My Personal Notes arrow_drop_up

I am a technology enthusiast who has a keen interest in programming I am pursuing Engineering in Computer Science from GEU, Dehradun I like to unwind by watching movies and English sitcomsI have a keen interest in music

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.