2015-07-01 29 views
5

也許這是我的英語,但在PHP Manual(引用波紋管)的解釋不能很好地回答我的問題。關於PHP的fseek()方法,究竟偏移量(位置)是什麼?

要移到文件結束之前的位置,您需要傳遞一個 負數的偏移量,並將其設置爲SEEK_END。

我有一個文件,我需要寫在它的(比方說)第五行。我應該如何制定正確的偏移量呢?

我知道它不是簡單的(5)行號。所以我猜測它的現有數據的總長度直到5號線的開始。 如果是這樣的話,每行文件是否有特定的長度,或者(很有可能)是基於行內容而變化的?如果它的變量我應該怎麼找出來?

任何意見,將不勝感激。

+2

尋求()與工作「字節」偏移量,而不是行號。除非你使用已知的固定長度的線條(它可以讓你做一些數學來計算偏移應該是什麼),那麼你需要一次讀取每一行以獲得你想要的偏移量...... 。電腦不能奇蹟般地猜測線路長度可能純粹是任意的 –

+0

非常感謝,@MarkBaker – Ali

回答

0

這裏是基於gnarf's answer here

<?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); 

這將改變(替換)sample.txt具有以下內容的示例:

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