我这段代码:
$file = fopen($path, 'r+');
flock($file, LOCK_EX);
// reading the file into an array and doing some stuff to it
for ($i=0; $i<count($array); $i++)
{
fwrite($file, $array[$i]);
}
flock($file, LOCK_UN);
fclose($file);
Run Code Online (Sandbox Code Playgroud)
基本上我想要做的是:打开文件>锁定它>读取它>做一些事情> 清除文件 >写入文件>解锁>关闭它.
问题是清算部分.我知道我可以做到这一点,fopen($file, 'w+')但然后阅读将是一个问题.也许我可以改变mode某种程度?
保罗,任何帮助都会受到赞赏
如果您使用指针设置为0 fseek,则可以这样运行ftruncate:
// reading the file into an array and doing some stuff to it
//1
fseek($handle,0); //Set the pointer to the first byte
//2
ftruncate($handle,filesize("yourfile.ext")); //from the first byte to the last truncate
//3 - File should be empty and still in writing mode.
for ($i=0; $i<count($array); $i++)
{
fwrite($file, $array[$i]);
}
Run Code Online (Sandbox Code Playgroud)
关注ftruncate这些问题,请考虑第二个问题:
如果size小于文件,则文件将截断为该大小.