Tuesday, October 7, 2025
HomeLanguagesPHP | SplFileObject ftruncate() Function

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:




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


Output:

Geeksfor

Program 2:




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


Output:

Geeksfor
Contribu
Article

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32340 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6708 POSTS0 COMMENTS
Nicole Veronica
11872 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6829 POSTS0 COMMENTS
Ted Musemwa
7090 POSTS0 COMMENTS
Thapelo Manthata
6780 POSTS0 COMMENTS
Umr Jansen
6784 POSTS0 COMMENTS