PHP在没有重写文件的情况下将数据写入文件中间的最佳方法是什么

Dan*_*iel 6 php file

我正在使用php(1GB +)中的大文本文件,我正在使用

file_get_contents("file.txt", NULL, NULL, 100000000,100); 
Run Code Online (Sandbox Code Playgroud)

要从文件中间获取数据,但如果我想将文件中的数据更改为与原始数据不同的更改,我将不得不重新编写整个文件.

如果数据大于原始数据,如何更改文件中的数据(可变长度)而不覆盖数据?我保留文件中不同数据块的索引及其字节位置.似乎唯一的选择是为每个数据分配x个字节,然后如果我想改变它就重写那个块......这个问题是它会占用比仅需要更多的空间null字节,写入需要更长的时间......而且仍然无法解决如何"删除"数据,因为文件的大小永远不会缩小......我真的需要一些帮助......

如果我为文件中的每个数据使用了前缀块,比如1 mb,那么我想输入的数据只是100kb,该条目需要10倍实际需要的空间,并且该条目永远不能更改为超过1mb的数据,因为它会覆盖超过第一个专用块...删除它是不可能的...希望这有任何意义......我不是在寻找替代方案,我希望在中间写入和更改数据文件,呵呵......

更新:是的,我想替换旧数据,但如果新数据扩展超过旧数据,我希望其余数据进一步推送到文件中...

考虑一下:0000000HELLODATA00000000零表示空格,没有...现在我想用SOMETHING替换HELLO,现在因为有些东西比hello大,只需在hello的起点写入就会扩展byond hello并开始覆盖数据.因此我希望将DATA推进到文件中,为SOMETHING腾出空间而不覆盖数据......呵呵

Bab*_*aba 10

要覆盖数据:

$fp = fopen("file.txt", "rw+");
fseek($fp, 100000000); // move to the position
fwrite($fp, $string, 100); // Overwrite the data in this position 
fclose($fp);
Run Code Online (Sandbox Code Playgroud)

注入数据

这是一个棘手的问题因为你必须要rewrite文件.它可以优化partial modificationpoint of injection,而不是整个文件

$string = "###INJECT THIS DATA ##### \n";
injectData("file.txt", $string, 100000000);
Run Code Online (Sandbox Code Playgroud)

使用的功能

function injectData($file, $data, $position) {
    $fpFile = fopen($file, "rw+");
    $fpTemp = fopen('php://temp', "rw+");

    $len = stream_copy_to_stream($fpFile, $fpTemp); // make a copy

    fseek($fpFile, $position); // move to the position
    fseek($fpTemp, $position); // move to the position

    fwrite($fpFile, $data); // Add the data

    stream_copy_to_stream($fpTemp, $fpFile); // @Jack

    fclose($fpFile); // close file
    fclose($fpTemp); // close tmp
}
Run Code Online (Sandbox Code Playgroud)