在 PHP 中使用固定长度缓冲区中的可变长度数据

Consuming variable lengths of data from a fixed length buffer in PHP

我有一个太大的文件,我无法一次将它读入一个字符串,但必须使用缓冲:

$fp = @fopen("bigfile", 'rb');
while (!feof($fp)) {
    //process buffer
}

为简单起见,假设文件包含一系列整数字符串对,其中整数包含字符串的长度。那么process buffer中我要实现的代码,就是unpack一个int,从buffer中读取那么多字符,然后重复

对于处理字符串跨越一个缓冲区到下一个缓冲区的情况,我很感激任何建议。我确定这个问题一定已经解决了,并且有一个设计模式,我只是不知道从哪里开始寻找。

如有任何帮助,我们将不胜感激。

不确定您是否正在寻找更聪明的解决方案,但直截了当是:

while (!feof($fp)) {
    $len = fread($fp, 2); // integer-2 bytes ...?
    // <--- add checks here  len($len)==2 and so on...
    $len = unpack('S', $len); // pick the correct format character from http://docs.php.net/function.pack

    while(!feof($fp) && $len) {
        $cbRead = $len < MAX_CHUNK_LEN ? $len : MAX_CHUNK_LEN;
        $buf = fread($fp, $cbRead);
        // <--- add checks here  len($buf)==$cbRead and so on...
        $len -= $cbRead;
        // ... process buf 
    }
    if ( $len!=0 ) {
        errorHandler();
    }
    else {
        processEndOfString();
    }
}