Skip to content

ftruncate()

What is the ftruncate() Function?

The ftruncate() function is a built-in PHP function that truncates the specified file to a specified length. This function is used to change the size of a file. If the file is extended, the new area is filled with null bytes (\0). The function returns true on success or false on failure. Note that ftruncate() does not alter the internal file pointer position.

Here's the basic syntax of the ftruncate() function:

The PHP syntax of ftruncate()

php
ftruncate(file, length);

Where file is the file pointer for the file to truncate, and length is the new size of the file.

How to Use the ftruncate() Function?

Using the ftruncate() function is straightforward. Here are the steps to follow:

  1. Open the file you want to manipulate using the fopen() function in the appropriate mode.
  2. Call the ftruncate() function, passing in the file pointer and the new size of the file.
  3. Close the file using the fclose() function.

Here's an example code snippet that demonstrates how to use the ftruncate() function:

php
<?php

$filename = 'myfile.txt';
$file = fopen($filename, 'r+');
if ($file) {
    ftruncate($file, 10);
    fclose($file);
}

In this example, we open the file myfile.txt using the fopen() function in read-write mode. We then use the ftruncate() function to truncate the file to a length of 10 bytes. We then close the file using the fclose() function.

Conclusion

The ftruncate() function is a useful tool in PHP for changing the size of a file. By following the steps outlined in this guide, you can easily use the ftruncate() function in your PHP projects to manipulate files.

Practice

What does the ftruncate() function do in PHP?

Dual-run preview — compare with live Symfony routes.