du656637962 2012-03-19 01:07
浏览 100
已采纳

使用fseek在最后一行之前插入字符串

I am trying to write a very basic registration module for blueimp.net's AjaxChat. I have a script that writes to the user config file.

$userfile = "lib/data/users.php";
$fh = fopen($userfile, 'a');
$addUser = "string_for_new_user";
fwrite($fh, $addUser);
fclose($fh);

But I need it to insert $addUser before the very last line, which is ?>

How would I accomplish this using fseek?

  • 写回答

2条回答 默认 最新

  • dourao1896 2012-03-19 01:29
    关注

    If you always know that the file ends with ?> and nothing more, you can:

    $userfile = "lib/data/users.php";
    $fh = fopen($userfile, 'r+');
    $addUser = "string_for_new_user
    ?>";
    fseek($fh, -2, SEEK_END);
    fwrite($fh, $addUser);
    fclose($fh);
    

    To further enhance the answer: you're going to want to open your file in mode r+ because of the following note regarding fseek:

    Note:

    If you have opened the file in append (a or a+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.

    fseek($fh, -2, SEEK_END) will place the position at the end of the file, and then move it backwards by 2 bytes (the length of ?>)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongmu6225 2012-03-19 01:39
    关注

    Another way to accomplish this is using the SplFileObject class (available as of PHP 5.1).

    $userfile = "lib/data/users.php";
    $addUser = "
    string_for_new_user
    ";
    $line_count = 0;
    
    // Open the file for writing
    $file = new SplFileObject($userfile, "w");
    
    // Find out number of lines in file
    while ($file->valid()) {
       $line_count++;
       $file->next();
    }
    
    // Jump to second to last line
    $file->seek($line_count - 1);
    
    // Write data
    $file->fwrite($add_user);
    

    I haven't tested this (I can't on the computer I'm using right now) so I'm not sure if that works exactly like that. The point here is really the cool seek() method of the SplFileObject which can seek by line rather than how fseek() seeks by bytes.

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Linux操作系统中的,管道通信问题
  • ¥15 请问这张multisim图的原理是什么,这是一个交通灯,是课程要求,明天要进行解析,但是我们组没一个人会,所以急要,今天要
  • ¥15 ansible tower 卡住
  • ¥15 等间距平面螺旋天线方程式
  • ¥15 通过链接访问,显示514或不是私密连接
  • ¥100 系统自动弹窗,键盘一接上就会
  • ¥50 股票交易系统设计(sql语言)
  • ¥15 调制识别中这几个数据集的文献分别是什么?
  • ¥15 使用c语言对日志文件处理
  • ¥15 请大家看看报错原因,为啥会这样