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


using fseek to insert string before last line

我正在为blueimp.net的AjaxChat编写一个非常基本的注册模块。我有一个脚本可以写入用户配置文件。

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

但我需要它在最后一行之前插入$addUser,这是?>

我将如何使用fseek实现这一点?

如果总是知道文件以?>结尾除此之外,你可以:

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

为了进一步增强答案:由于以下关于fseek:的注意事项,您将希望以r+模式打开文件

注意:

如果您以追加(a或a+)模式打开文件对文件的写入将始终被追加,而与文件无关位置,并且调用fseek()的结果将是未定义的。

fseek($fh, -2, SEEK_END)将把位置放在文件的末尾,然后向后移动2个字节(?>的长度)

实现这一点的另一种方法是使用SplFileObject类(从PHP 5.1开始提供)

$userfile = "lib/data/users.php";
$addUser = "'nstring_for_new_user'n";
$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);

我还没有测试过这个(我现在用的电脑无法测试),所以我不确定它是否真的是这样。这里的重点实际上是SplFileObject的酷seek()方法,它可以按行搜索,而不是fseek()如何按字节搜索。