PHP - 删除文件的最后一个字符 [英] PHP - Remove last character of file

查看:121
本文介绍了PHP - 删除文件的最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  $ contents = file_get_contents($ path)

我有一个小小的php脚本,用于删除文件的最后一个字符。 ;
rtrim($ contents);
$ contents = substr($ contents,0,-1);
$ fh = fopen($ path,'w')或死(无法打开文件);
fwrite($ fh,$ contents);
fclose($ fh);所以它读取文件内容,去掉最后一个字符,然后截断文件,然后写入文件串回它。
这一切工作正常。我的担心是,这个文件可能包含大量的数据,然后file_get_contents()调用将把所有这些数据保存在内存中,这有可能使我的服务器内存最大化。



是否有更有效的方法去除文件中的最后一个字符?

谢谢

解决方案

试试这个

  $ fh = fopen($ path,'r +')或死(无法打开文件); 

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

如需更多帮助,请参阅


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

解决方案

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

这篇关于PHP - 删除文件的最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆