PHP - Remove last character of file

浪子不回头ぞ 提交于 2019-11-30 23:50:18

问题


I have a little php script that removes the last character of a file.

$contents = file_get_contents($path);
rtrim($contents);
$contents = substr($contents, 0, -1);
$fh = fopen($path, 'w') or die("can't open file");
fwrite($fh, $contents);
fclose($fh);    

So it reads in the file contents, strips off the last character and then truncates the file and writes the string back to it. This all works fine.

My worry is that this file could contain a lot of data and the file_get_contents() call would then hold all this data in memory which could potentially max out my servers memory.

Is there a more efficient way to strip the last character from a file?

Thanks


回答1:


Try this

$fh = fopen($path, 'r+') or die("can't open file");

$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);
fclose($fh); 

For more help see this



来源:https://stackoverflow.com/questions/8354384/php-remove-last-character-of-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!