PHP Streams函数

PHP stream_copy_to_stream() 函数将数据从一个流复制到另一个流。它将最多 length 个字节的数据从当前位置(或从偏移位置,如果指定)从一个流复制到另一个流。如果length为空,则将复制所有剩余内容。

语法

stream_copy_to_stream(from, to, length, offset) 

参数

from必填。 指定源流。
to必填。 指定目标流。
length可选。 指定要复制的最大字节数。默认情况下,将复制剩余的所有字节。
offset可选。 指定开始复制数据的偏移量。默认值为 0。

返回值

返回复制的字节总数,失败时返回 false。

示例:stream_copy_to_stream()示例

让我们假设我们有一个名为test.txt的文件。该文件包含以下内容:

This is a test file.
It contains dummy content. 

在下面的示例中,stream_copy_to_stream()函数用于将此文件的前 25 个字节复制到 part1.txt 并保留在 part2.txt 中。

<?php
//打开源文件进行读取
$src = fopen("test.txt", "r");

//创建目标文件
$dest1 = fopen("part1.txt", "w");
$dest2 = fopen("part2.txt", "w");

echo stream_copy_to_stream($src, $dest1, 25) . " bytes copied to part1.txt\n";
echo stream_copy_to_stream($src, $dest2) . " bytes copied to part2.txt\n";

//关闭所有文件
fclose($src);
fclose($dest1);
fclose($dest2);

//读取并显示文件内容
echo "\npart1.txt contains:\n";
echo file_get_contents("part1.txt");
echo "\n\npart2.txt contains:\n";
echo file_get_contents("part2.txt");
?> 

上述代码的输出将是:

25 bytes copied to part1.txt
23 bytes copied to part2.txt

part1.txt contains:
This is a test file.
It 

part2.txt contains:
contains dummy content.