Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-删除文件的最后一个字符_Php_File Io_Trim - Fatal编程技术网

PHP-删除文件的最后一个字符

PHP-删除文件的最后一个字符,php,file-io,trim,Php,File Io,Trim,我有一个小php脚本,可以删除文件的最后一个字符 $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); 因此,它读入文件内容,去掉最后一个字符,然后截断文件并将字符串写回文件。 这

我有一个小php脚本,可以删除文件的最后一个字符

$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);    
因此,它读入文件内容,去掉最后一个字符,然后截断文件并将字符串写回文件。 这一切都很好

我担心的是,这个文件可能包含大量数据,而file\u get\u contents()调用会将所有这些数据保存在内存中,这可能会使我的服务器内存最大化

有没有更有效的方法从文件中删除最后一个字符

谢谢你试试这个

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

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

有关更多帮助,请参见出现的将文件截断为0的

啊,可能是因为fopen用的是w。但将其设置为r似乎不起作用?非常感谢azat。现在效果很好:)优雅的解决方案,甚至在CIf中也不知道该函数。如果要在修剪尾随字符后添加字符,需要将
fseek()
设置为当前大小。如果不这样做,将在文件的新大小和旧大小之间获得空字符<代码>$position=fstat($fh)['size']-1
ftruncate($fh,$position)
fseek($fh,$position)帮助我删除CSV文件中的最后一个字符A0