W3docs

ftruncate()

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,

The ftruncate() function in PHP resizes an open file to an exact number of bytes. It can both shrink a file (cutting off everything past a given length) and grow it (padding the extra space with null bytes). This page explains the syntax, the return value, the rules around the file pointer, and the common real-world uses — clearing a log, fixing a corrupted record, or pre-allocating space — with runnable examples.

What the ftruncate() Function Does

ftruncate() truncates an open file to the length you specify, measured in bytes:

  • If the file is larger than length, the extra bytes are discarded.
  • If the file is smaller than length, it is extended and the new area is filled with null bytes (\0).
  • If length equals 0, the file is emptied — a common way to clear a file without deleting it.

It returns true on success and false on failure. Importantly, ftruncate() does not move the internal file pointer. If you wrote to byte 50 and then truncate to 10 bytes, the pointer is still at 50, so your next write would start there and re-extend the file with null bytes. Use rewind() or fseek() to reposition the pointer afterward.

Syntax

ftruncate(resource $stream, int $size): bool
  • $stream — the file pointer returned by fopen(). The file must be opened in a writable mode (r+, w, w+, a+, etc.). Opening with r (read-only) makes ftruncate() fail.
  • $size — the new size of the file in bytes (a non-negative integer).

How to Use ftruncate()

The pattern is always the same three steps:

  1. Open the file in a writable mode with fopen().
  2. Call ftruncate() with the file pointer and the target size.
  3. Close the file with fclose().

The example below writes a known string, truncates it to 5 bytes, and reads the result back so you can see exactly what survives:

<?php

$filename = 'demo.txt';

// Open for reading and writing; create if it does not exist.
$file = fopen($filename, 'w+');

fwrite($file, 'Hello, World!'); // 13 bytes
ftruncate($file, 5);            // keep only the first 5 bytes

rewind($file);                  // pointer was at 13 — move it back to 0
echo fread($file, 1024);        // Hello

fclose($file);

The output is:

Hello

Only Hello remains because the file was cut to 5 bytes. Note the rewind() call — without it fread() would start at byte 13 (past the end) and return nothing.

Growing a File with Null Bytes

When $size is larger than the current file, ftruncate() extends it and pads the new region with \0. This is useful for pre-allocating a fixed-size file:

<?php

$file = fopen('padded.txt', 'w+');

fwrite($file, 'abc');     // 3 bytes
ftruncate($file, 8);      // grow to 8 bytes; 5 null bytes added

clearstatcache();         // discard any cached stat info
echo filesize('padded.txt') . " bytes\n";

fclose($file);

The output is:

8 bytes

The file is now 8 bytes — the original abc followed by five null (\0) bytes. The clearstatcache() call matters because PHP caches the result of stat-based functions like filesize() within a request; if you had already read the file's size earlier, the cached value could be stale after a truncate.

Common Use Cases

  • Clearing a file in place. ftruncate($file, 0) empties a log or cache file while keeping its inode, permissions, and any other handles open. This is safer than deleting and recreating it.
  • Removing a trailing record. Read the file, find where the last entry begins, and truncate to that offset to drop it without rewriting the whole file.
  • Fixing a partially written file. If a write was interrupted, truncating back to a known-good length restores a valid state.
  • Pre-allocating space. Reserve a fixed-size file up front (for example, a binary index) before filling it in.

Gotchas

  • Read-only handles fail. Opening with r and calling ftruncate() returns false and emits a warning. Use r+ if you need to keep existing content but still write.
  • The pointer does not move. Always rewind() or fseek() before reading or appending after a truncate, or you may create unexpected null-byte padding.
  • Stale stat cache. filesize() and similar functions may report the old size right after truncating; call clearstatcache() to get the current value.
  • length is bytes, not characters. With multi-byte (UTF-8) text, truncating mid-character can corrupt the last character.
  • fopen() — open the file before truncating.
  • fwrite() — write data into the file.
  • fread() — read the file's contents back.
  • fseek() / rewind() — reposition the pointer after truncating.
  • fclose() — close the file when you are done.

Conclusion

ftruncate() is the precise way to resize an open file in PHP — shrinking it by cutting off trailing bytes, or growing it with null-byte padding. The key things to remember are that the file must be open in a writable mode, that the function never moves the file pointer, and that clearstatcache() may be needed to see the new size. Used with fopen(), fwrite(), and fclose(), it handles tasks from clearing logs to repairing partially written files.

Practice

Practice
What does the ftruncate() function do in PHP?
What does the ftruncate() function do in PHP?
Was this page helpful?