Ali*_*Ali 5 php fseek file-handling
也许它是我的英语,但PHP手册中的解释(引用贝娄)并不能很清楚地回答我的问题.
要移动到文件结尾之前的位置,您需要在偏移量中传递负值并将其设置为SEEK_END.
我有一个文件,我需要写它(让我们说)第5行.我应该如何锻炼正确的偏移?
我知道它不仅仅是(5)行号.所以我猜测现有数据的总长度直到第5行的开头.如果是这样,每行文件有任何特定长度,或者(很可能)它是基于行的内容的变量?如果它的变量应该如何找到它?
任何建议将不胜感激.
小智 0
这是一个基于gnarf 答案的示例
<?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);
Run Code Online (Sandbox Code Playgroud)
它将更改(替换)sample.txt为以下内容:
line one
line two
line three
line four
line five
Run Code Online (Sandbox Code Playgroud)
到
line one
line two
Here is the new value for the line 3line three
line four
line five
Run Code Online (Sandbox Code Playgroud)