PHP | SplFileObject ftruncate() Function

The SplFileObject::ftruncate() function is an inbuilt function of Standard PHP Library (SPL) in PHP which is used to truncates the file size in bytes.

Syntax:

bool SplFileObject::ftruncate( $length )

Parameters: This function accept single parameter $length which specified the length of truncate of the file.



Return values: This function returns True on success or False on failure.

Below Programs illustrate the SplFileObject ftruncate() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a file named "gfg.txt" which
// containing data "GeeksforGeeks"
$gfg = new SplFileObject("gfg.txt", "w+");
$gfg->fwrite("GeeksforGeeks");
  
// Truncate file 
$gfg->ftruncate(8);
  
// Rewind and reading data from file
$gfg->rewind();
  
// Print result after truncate
echo $gfg->fgets();
?>

chevron_right


Output:

Geeksfor

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
// Create an Array
$GFG = array(
    "dummy.txt",
    "gfg.txt",
    "frame.txt"
    );
   
// Creating Spl Object
foreach ($GFG as &$arr) {
    $file = new SplFileObject($arr);
       
    // Truncate file 
    $file->ftruncate(8);
       
    // Rewind and reading data from file
    $file->rewind();
       
    // Print result after truncate
    echo $file->fgets();
}
?>

chevron_right


Output:

Geeksfor
Contribu
Article

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.