php的fread函数的一个巨大的坑

本文详细解析PHP fread函数的工作原理,强调其在读取文件时的限制与条件,特别是与chunksize相关的问题。通过实例代码展示如何正确使用fread进行文件读取,避免常见错误。

先看看fread的manual,如下:

http://php.net/manual/en/function.fread.php

fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met:

  • length bytes have been read
  • EOF (end of file) is reached
  • a packet becomes available or the socket timeout occurs (for network streams)
  • if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.

中文:

fread() 从文件指针 file 读取最多 length 个字节。该函数在读取完最多 length 个字节数,或到达 EOF 的时候,或(对于网络流)当一个包可用时,或(在打开用户空间流之后)已读取了 8192 个字节时就会停止读取文件,视乎先碰到哪种情况。

返回所读取的字符串,如果出错返回 false。

 

结论:大家要注意上面红色的地方,一定要判断fread的返回值。我就是没有看文档,以为需要多少,就能读到多少。结果当读取的字节数过大时(与chunk size有关,好像是4K),各种出错。(这也与python的误导有关,因为python的sys.stdin.read就不是这样,我是参考了python的写法)

参考如下代码:

$v_content = '';
    while (strlen($v_content) < $v_len[1]) {
        $v_content .= fread(STDIN, $v_len[1] - strlen($v_content));
    }

  

转载于:https://www.cnblogs.com/hxdoit/p/5532128.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值