【问题标题】:About PHP's fseek() method, what exactly offset (position) is?关于 PHP 的 fseek() 方法,究竟什么是偏移量(位置)?
【发布时间】:2015-09-18 11:42:42
【问题描述】:

也许是我的英语,但PHP Manual(引用如下)中的解释并没有很清楚地回答我的问题。

要移动到文件结尾之前的位置,您需要传递一个 偏移量中的负值,并将其设置为 SEEK_END。

我有一个文件,我需要写在它的(比如说)第 5 行。我应该如何锻炼它的正确偏移量?

我知道它不仅仅是 (5) 行号。所以我猜它是现有数据的总长度,直到第 5 行的开头。 如果是这样,每行文件是否有任何特定长度,或者(很可能)它是基于行内容的变量?如果它的变量我应该如何找到它?

任何建议将不胜感激。

【问题讨论】:

  • seek() 使用“字节”偏移量,而不是行号。除非您使用已知的固定长度的行(这可以让您做一些数学运算来计算偏移量应该是多少),否则您需要一次读取每一行以获得您想要的偏移量...... . 计算机无法神奇地猜测行长度何时可能是纯任意的
  • 非常感谢,@MarkBaker

标签: php file-handling fseek


【解决方案1】:

这里是一个基于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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 2018-02-10
    • 1970-01-01
    相关资源
    最近更新 更多