本文介绍了使用fseek在最后一行之前插入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我如何使用fseek完成此操作?

How would I accomplish this using fseek?

推荐答案

如果您始终知道文件以?>结尾,仅此而已,您可以:

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\n?>";
fseek($fh, -2, SEEK_END);
fwrite($fh, $addUser);
fclose($fh);

要进一步增强答案:由于r+中打开文件. php"rel =" nofollow>关于fseek的注释:

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

如果您已以附加(a或a +)模式打开文件,则所有数据 无论文件是什么,写入文件都会始终被追加 位置,调用fseek()的结果将是不确定的.

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)会将位置放置在文件的末尾,然后向后移动2个字节(?>的长度)

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

这篇关于使用fseek在最后一行之前插入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:01
查看更多