ZetCode

PHP ftruncate 函数

最后修改于 2025 年 4 月 3 日

PHP 的 ftruncate 函数将文件截断到指定的长度。 它对于调整文件大小或清除文件内容,同时保留文件句柄非常有用。

基本定义

ftruncate 函数将一个打开的文件截断为给定的尺寸。 它有两个参数:文件指针和要截断的尺寸。

语法:ftruncate(resource $stream, int $size): bool。 该函数在成功时返回 true,失败时返回 false。 文件必须已打开用于写入。

基本 ftruncate 示例

这展示了 ftruncate 清空文件的最简单用法。

basic_ftruncate.php
<?php

declare(strict_types=1);

$filename = "data.txt";
$file = fopen($filename, "r+");

if ($file) {
    ftruncate($file, 0);
    fclose($file);
    echo "File truncated successfully.";
} else {
    echo "Failed to open file.";
}

这以读写模式打开一个文件,并将其截断为 0 字节。 在操作之后,文件句柄被正确关闭。 始终检查文件打开是否成功。

截断到特定大小

ftruncate 可以将文件大小调整到任何指定的长度,而不仅仅是零。

specific_size.php
<?php

declare(strict_types=1);

$filename = "data.txt";
$file = fopen($filename, "r+");

if ($file) {
    ftruncate($file, 100);
    fclose($file);
    echo "File resized to 100 bytes.";
} else {
    echo "Failed to open file.";
}

这会将文件调整为正好 100 字节。 如果文件较大,则会被截断。 如果较小,则会使用空字节进行扩展。 文件指针位置不会因本次操作而改变。

错误处理

在处理文件系统操作时,适当的错误处理至关重要。

error_handling.php
<?php

declare(strict_types=1);

$filename = "data.txt";
$file = fopen($filename, "r+");

if ($file === false) {
    die("Failed to open file.");
}

if (!ftruncate($file, 0)) {
    fclose($file);
    die("Failed to truncate file.");
}

fclose($file);
echo "File truncated successfully.";

此示例展示了强大的错误处理。 它同时检查文件打开和截断结果。 在失败的情况下,资源会被正确清理。 始终处理潜在的文件系统错误。

与文件写入相结合

ftruncate 经常与文件写入操作一起使用。

with_writing.php
<?php

declare(strict_types=1);

$filename = "log.txt";
$file = fopen($filename, "r+");

if ($file) {
    ftruncate($file, 0);
    fwrite($file, "New log content\n");
    fclose($file);
    echo "Log file cleared and rewritten.";
} else {
    echo "Failed to open log file.";
}

这会在写入新内容之前清除日志文件。 该序列确保没有旧内容残留。 文件指针在截断后位于位置 0,准备好写入。 这是日志轮换的常用模式。

文件扩展示例

ftruncate 也可以通过指定更大的尺寸来扩展文件。

file_extension.php
<?php

declare(strict_types=1);

$filename = "data.bin";
$file = fopen($filename, "r+");

if ($file) {
    $newSize = 1024; // 1KB
    if (ftruncate($file, $newSize)) {
        echo "File extended to {$newSize} bytes.";
    } else {
        echo "Failed to extend file.";
    }
    fclose($file);
} else {
    echo "Failed to open file.";
}

这会将文件扩展到 1KB 的大小。 新空间将填充空字节。 此技术对于预分配文件空间很有用。 请注意,操作必须有可用的磁盘空间才能成功。

最佳实践

来源

PHP ftruncate 文档

本教程涵盖了 PHP 的 ftruncate 函数,并附有实际示例,展示了它在不同场景中的用法。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 PHP 文件系统函数