简体   繁体   English

php fwrite和fopen在同一条语句中

[英]php fwrite and fopen in same statement

I saw a php script that wrote to a file like this: 我看到一个php脚本写入了这样的文件:

fwrite(fopen($logFileName, "a"), $logData);

That is definitely more succint than: 绝对比以下内容更简洁:

$handle = fopen($logFileName, "a");
fwrite($handle, $logData);
fclose($handle);

Especially for one-liners, or when you want to write to a file in a single statement. 特别是对于单行代码,或者要在单个语句中写入文件的情况。

Is it ok not to use fclose on the first approach? 可以不要在第一种方法上使用fclose吗? or is that code considered buggy in a way? 还是该代码在某种程度上被认为是越野车?

Bonus question: is there a one-liner similar to file_put_contents($logFileName, $logData) but that allows me to append to a file instead of overwritting it? 额外的问题:是否有类似于file_put_contents($logFileName, $logData)但是允许我追加到文件中而不是覆盖它?

Thanks :-) 谢谢 :-)

The main mistake in this one-liner is the missing fclose. 这种单线的主要错误是缺少fclose。 Not a good style at all. 根本不是一个好的风格。

However, if this is the only statement or the programmer doesn't care about some open file handles within the script-lifetime, that might be ok. 但是,如果这是唯一的声明,或者程序员不在乎脚本生存期内的某些打开文件句柄,则可能没问题。

Caution: Normally, php cleans up any resources allocated during runtime when a script terminates. 注意:通常,当脚本终止时,php会清除运行时分配的所有资源。 This is especially true for CGI-calls. 对于CGI调用尤其如此。 I guess, this is also true for non-CGI-calls (php module hosted within the webserver), but you should be aware of that. 我猜想,对于非CGI调用(Web服务器中托管的php模块)也是如此,但是您应该意识到这一点。

And for your bonus question: The answer is yes, although i guess you wanted something different. 对于您的奖金问题:答案是肯定的,尽管我猜您希望有所不同。

file_put_contents($filename, file_get_contents($filename).$newContent);

Literally, your question has been answered here, semantically, this is not even worth a try because you read the whole file into memory just to put it back again. 从字面上看,您的问题已在语义上得到了回答,这甚至不值得尝试,因为您将整个文件读入内存只是为了再次将其放回去。

But, what prevents you from writing that function on your own? 但是,是什么阻止您自己编写该函数呢?

function file_put_additional_contents( $filename, $content ){
   $file = fopen($filename, "a");
   fwrite($file, $content);
   fclose($file);
}

[edit] As Symeon Quimby pointed out, there is a special flag for file_put_contents: [edit]正如Symeon Quimby所指出的,file_put_contents有一个特殊的标志:

file_put_contents($filename, $content, FILE_APPEND);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM