使用PHP优化内存使用情况和更改文件内容



在这样的函数中

function download($file_source, $file_target) {
    $rh = fopen($file_source, 'rb');
    $wh = fopen($file_target, 'wb');
    if (!$rh || !$wh) {
        return false;
    }
    while (!feof($rh)) {
        if (fwrite($wh, fread($rh, 1024)) === FALSE) {
            return false;
        }
    }
    fclose($rh);
    fclose($wh);
    return true;
}

使用我的自定义字符串重写文件的最后几个字节的最佳方法是什么?

谢谢!

尝试

$yourString = "The New String World";
$fileTarget = "log.txt";
// Replace Last bytes with this new String
replaceFromString($fileTarget, $yourString);

示例2

// Replace last 100bytes form file A to file B
replaceFromFile("a.log", "b.log", 100, - 100);

使用的功能

function replaceFromString($file, $content, $offsetIncrement = 0, $whence = SEEK_END) {
    $witePosition = - strlen($content);
    $wh = fopen($file, 'rb+');
    fseek($wh, $witePosition + $offsetIncrement, $whence);
    fwrite($wh, $content);
    fclose($wh);
}
function replaceFromFile($fileSource, $fileTarget, $bytes, $offest, $whence = SEEK_END) {
    $rh = fopen($fileSource, 'rb+');
    $wh = fopen($fileTarget, 'rb+');
    if (! $rh || ! $wh) {
        return false;
    }
    fseek($wh, $offest, $whence);
    if (fwrite($wh, fread($rh, $bytes)) === FALSE) {
        return false;
    }
    fclose($rh);
    fclose($wh);
    return true;
}

相关内容

最新更新