dongqiu3254 2017-10-27 11:33
浏览 120

如何在写入过程中检测到Gzip和Bzip2文件的溢出?

I need to determine that the file exceeds the specified size while it is being written. When i reach the specified size, i must stop writing and throw a exception.

Example for a normal file:

$handle = fopen($filename, 'wb');
while (true) {
    // its work
    if (fstat($handle)['size'] + strlen($string) > BYTE_LIMIT) {
        throw SizeOverflowException::withLimit(BYTE_LIMIT);
    }

    fwrite($this->handle, $string);
}
fclose($handle);

Or i can independently count the used bytes

$handle = fopen($filename, 'wb');
$used_bytes = 0;
while (true) {
    if ($used_bytes + strlen($string) > BYTE_LIMIT) {
        throw SizeOverflowException::withLimit(BYTE_LIMIT);
    }

    fwrite($this->handle, $string);
    $used_bytes += strlen($string);
}
fclose($handle);

Example write Gzip:

$handle = gzopen($filename, 'wb9');
while (true) {
    // not work
    // fstat($handle) === false
    //if (fstat($handle)['size'] + strlen($string) > BYTE_LIMIT) {
    //    throw SizeOverflowException::withLimit(BYTE_LIMIT);
    //}

    gzwrite($this->handle, $string);
}
gzclose($handle);

Similarly for Bzip2:

$handle = bzopen($filename, 'w');
while (true) {
    // not work
    // fstat($handle) === false
    //if (fstat($handle)['size'] + strlen($string) > BYTE_LIMIT) {
    //    throw SizeOverflowException::withLimit(BYTE_LIMIT);
    //}

    bzwrite($this->handle, $string);
}
bzclose($handle);

I understand why fstat() does not work in this case, but how can i solve this problem?

Now i can calculate only how many bytes will be used in uncompressed mode.

  • 写回答

1条回答 默认 最新

  • drvxclagw656708070 2017-10-27 22:26
    关注

    You can instead compress incrementally in memory using deflate_init and deflate_add, using the encoding ZLIB_ENCODING_GZIP, and write the compressed data out normally with fwrite. Then you can count the compressed bytes written and stop at your specified size.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?