SplFileObject::ftruncate

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::ftruncateファイルを指定した長さに丸める

説明

public SplFileObject::ftruncate(int $size): bool

ファイルを size バイトに丸めます。

パラメータ

size

丸めるサイズ。

注意:

size がファイルのサイズより大きい場合、ファイルは null バイトで拡大されます。

size がファイルのサイズより小さい場合、余分なデータは失われます。

戻り値

成功した場合に true を、失敗した場合に false を返します。

例1 SplFileObject::ftruncate() の例

<?php
// "Hello World!" が格納されるファイルを作成する
$file = new SplFileObject("/tmp/ftruncate", "w+");
$file->fwrite("Hello World!");

// 5 バイトに丸める
$file->ftruncate(5);

// 巻き戻してデータを読み出す
$file->rewind();
echo
$file->fgets();
?>

上の例の出力は、 たとえば以下のようになります。

Hello

参考

  • ftruncate() - ファイルを指定した長さに丸める

add a note

User Contributed Notes 1 note

up
7
irvinezega at hotmail dot com
5 years ago
I suppose a fair number of us know this:

However, for those who don't:-

If you are truncating a file, say, to $fileObject->ftruncate(0), then, it may be advisable to call $fileObject->fseek(0) first (before you call '$fileObject->ftruncate').

On inspection, I was encountering 'NULL' characters at the beginning of a, or the, file.

Hence, from what I have surmised; when 'ftruncate()' is called, the file pointer does NOT move to the beginning (or, at least, the required position) of the file.

This issue cost me a fair amount of time to figure out, so I hope it helps someone.
To Top