这个fopen代码可以改进吗
我看到这段代码首先创建文件,关闭它,然后使用 'a'
打开它,写入它,然后关闭它。有没有办法简化一下。这个想法是,如果文件名存在,则需要将其覆盖。我也不明白unset
的意义。有必要吗?
$fp = fopen($file_name, 'w');
fclose($fp);
unset($fp);
$fp = fopen($file_name, 'a');
fputs($fp, "sometext");
fclose($fp);
unset($fp);
I'm seeing that this code first creates the file, closes it, then opens it with 'a'
, writes to it, then closes it. Is there a way to simplify it. The idea is that if the file name exists, it needs to be overwritten. I also don't understand the point of unset
. Is it necessary?
$fp = fopen($file_name, 'w');
fclose($fp);
unset($fp);
$fp = fopen($file_name, 'a');
fputs($fp, "sometext");
fclose($fp);
unset($fp);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 php.net,在 fopen 的 'w' 模式下: Open for write only;将文件指针放在文件的开头并将文件截断为零长度。如果该文件不存在,请尝试创建它。
换句话说,打开以进行写入,并根据需要覆盖或创建。无需使用附加模式。
From php.net, under the 'w' mode in fopen: Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
In other words, open for writing, and overwrite or create as necessary. No need to use append mode.
而且,不,
unset()
对于您的情况来说是没有意义的。And, No,
unset()
is pointless in your case.