Open In App

PHP ftruncate( ) Function

Last Updated : 23 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The ftruncate() function in PHP is an inbuilt function that 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 the size specified in the parameter is larger than the file then the file is extended with null bytes and if the 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 that specifies the file.
  2. size : It is a mandatory parameter that 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 the size specified in the parameter is larger than the file then the file is extended with null bytes and if the size specified is smaller than the file then the file is truncated to that size

Examples of PHP truncate() Function

Below programs illustrate the ftruncate() function:

Example 1: Truncating a File

In this example, we will use of the ftruncate() function to truncate a file. First, the program opens a file and determines its initial size. Then, it truncates the file to a smaller size using ftruncate(), and finally, the new size of the file is displayed.

php
<?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

Example 2: Extending a File with ftruncate

In this example, we demonstrate how ftruncate() can be used to extend the file by specifying a larger size than the current file length. The file is extended with null bytes when truncated to a larger size.

php
<?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

Next Article

Similar Reads

three90RightbarBannerImg
  翻译: