PHP高效读取并删除文件第一行内容
'读取c.txt的内容'
$file = 'c1.txt';$content = file($file);
// 获取第一行内容$firstLine = trim($content[0]);// 删除第一行array_shift($content);// 删除c.txt的内容file_put_contents($file, implode('', $content));
这段代码的获取第一行内容在删除第一行内容的功能,能用其它方式直接获取第一行内容后直接删除第一行内容吗?而不是覆写内容:
是的,可以使用fopen和fgets函数来实现获取第一行内容并删除第一行的功能,而不是覆写整个文件。php$file = 'c1.txt';
// 打开文件$handle = fopen($file, 'r+');
// 获取第一行内容$firstLine = fgets($handle);
// 将文件指针移动到第二行开头rewind($handle);fgets($handle);
// 获取剩余内容$remainingContent = '';while (!feof($handle)) { $remainingContent .= fgets($handle);}
// 将剩余内容写回文件ftruncate($handle, 0);rewind($handle);fwrite($handle, $remainingContent);
// 关闭文件fclose($handle);
这样可以直接获取第一行的内容并删除第一行,而不是覆写整个文件。
原文地址: https://www.cveoy.top/t/topic/pmH9 著作权归作者所有。请勿转载和采集!