也许是我的英语,但PHP手册中的解释(引用如下)并没有很清楚地回答我的问题。
要移动到文件末尾之前的位置,需要传递偏移中的负值,并将where设置为SEEK_END。
我有一个文件,我需要在第5行写。我应该如何训练正确的偏移量?
我知道这不仅仅是行号。所以我猜它是到第5行开始的现有数据的总长度。如果是的话,文件的每一行都有特定的长度吗?或者(很可能)它是根据行的内容而变化的?如果它是可变的,我该如何找到它?
如有任何建议,我们将不胜感激。
这里有一个基于gnaf答案的例子
<?php
$targetFile = './sample.txt';
$tempFile = './sample.txt.tmp';
$source = fopen($targetFile , 'r');
$target = fopen($tempFile, 'w');
$whichLine = 5;
$whatToReplaceWith = 'Here is the new value for the line ' . $whichLine;
$lineCounter = 0;
while (!feof($source)) {
if (++$lineCounter == $whichLine) {
$lineToAddToTempFile = $whatToReplaceWith;
} else {
$lineToAddToTempFile = fgets($source);
}
fwrite($target, $lineToAddToTempFile);
}
unlink($targetFile);
rename($tempFile, $targetFile);
将CCD_ 1更改(替换)为以下内容:
line one
line two
line three
line four
line five
至
line one
line two
Here is the new value for the line 3line three
line four
line five