php的fread函数的一个巨大的坑
2016-05-26 18:00
537 查看
先看看fread的manual,如下:
http://php.net/manual/en/function.fread.php
fread() reads up to
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。
[b]结论:[/b]大家要注意上面红色的地方,一定要判断fread的返回值。我就是没有看文档,以为需要多少,就能读到多少。结果当读取的字节数过大时(与chunk size有关,好像是4K),各种出错。(这也与python的误导有关,因为python的sys.stdin.read就不是这样,我是参考了python的写法)
参考如下代码:
http://php.net/manual/en/function.fread.php
fread() reads up to
lengthbytes from the file pointer referenced by
handle. Reading stops as soon as one of the following conditions is met:
lengthbytes 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。
[b]结论:[/b]大家要注意上面红色的地方,一定要判断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)); }
相关文章推荐
- PHP——大话PHP设计模式——魔术方法
- Package php5 have no installation candidate。
- vsftp服务配置详解
- 并发下常见的加锁及锁的PHP具体实现
- phpcms后台获取当前登录账号的数据的代码:
- PHP排序和MYSQL排序
- Yii 查询 搜索
- php 二维数组打乱顺序
- PHP解决某些特殊汉字符或汉字转码后成乱码或者空白的问题
- yii2入门实例
- PHP无乱码截取中文字符串
- wampserver安装(php的环境)
- YII1.1分页
- php代码一样,编码不同报错
- PHP 留言板
- PHP XDEBUG
- workerman和thinkphp完美结合使用
- PHP浮点数的精确计算BCMath
- php函数使用小技巧
- 使用msmtp 发送邮件