zoukankan      html  css  js  c++  java
  • php的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));
        }
    

      

  • 相关阅读:
    03.《架构漫谈》阅读笔记
    02.《架构漫谈》阅读笔记
    03.《架构之美》阅读笔记
    02.《架构之美》阅读笔记
    01.《架构之美》阅读笔记
    软件架构中的质量属性--以淘宝网为例(小论文)
    MVC框架介绍分析
    论面向服务架构设计及其应用
    1.26学习进度总结
    1.24学习进度总结
  • 原文地址:https://www.cnblogs.com/hxdoit/p/5532128.html
Copyright © 2011-2022 走看看