打开txt文件抓取数字计数+1并再次保存


Open txt file grab the number count +1 and save it again

我有一个文本文件number.txt里面只有数字1 .我正在使用下面的代码打开文件,获取数字,添加 1,更新内容(必须是 2)并再次保存。我的代码不起作用。有什么建议吗?

$fp = fopen('number.txt', 'c+');
flock($fp, LOCK_EX);
$count = (int)fread($fp, filesize('number.txt'));
ftruncate($fp, 0);
fseek($fp, 0);
fwrite($fp, $count + 1);
flock($fp, LOCK_UN);
fclose($fp);

我有用

<?php
   $handle = fopen("test.txt", "r+");
   if ($handle) {
   $buffer = fgets($handle, 10);
   $nCount = (int)$buffer;
   rewind($handle );
   fputs($handle, $nCount+1);
   fclose($handle);
   }
?>

你应该能够做到这一点

$path = 'number.txt';
file_put_contents($path, 1+(int)file_get_contents($path));