我试图用PHP编写一个文件,这是我正在使用的代码(从这个答案到前面的问题):
$fp = fopen("counter.txt", "r+");
while(!flock($fp, LOCK_EX)) { // acquire an exclusive lock
// waiting to lock the file
}
$counter = intval(fread($fp, filesize("counter.txt")));
$counter++;
ftruncate($fp, 0); // truncate file
fwrite($fp, $counter); // set your data
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
fclose($fp);读取部分工作正常,如果文件被读取,它的内容将被很好地读取,也就是说,如果文件包含2289,那么2289就会被读取。
问题是,当它将值递增并重写到该文件时,[NUL][NUL][NUL][NUL][NUL][NUL][NUL][NUL]1就会被写入。
我遗漏了什么?为什么要写空字符?
发布于 2013-08-15 15:28:49
编辑2:
用羊群试试这个(测试过)
如果文件未被锁定,它将抛出一个异常(请参阅添加的行)if(.
我从这个被接受的答案那里借用了异常片段。
<?php
$filename = "numbers.txt";
$filename = fopen($filename, 'a') or die("can't open file");
if (!flock($filename, LOCK_EX)) {
throw new Exception(sprintf('Unable to obtain lock on file: %s', $filename));
}
file_put_contents('numbers.txt', ((int)file_get_contents('numbers.txt'))+1);
// To show the contents of the file, you
// include("numbers.txt");
fflush($filename); // flush output before releasing the lock
flock($filename, LOCK_UN); // release the lock
fclose($filename);
echo file_get_contents('numbers.txt');
?>发布于 2015-03-11 20:56:11
您缺少的是倒带()。如果没有它,在截断到0字节后,指针仍然不在开头(参考文献)。因此,当您编写新值时,它会将其与文件中的NULL放在一起。
此脚本将读取当前计数的文件(如果不存在,则创建该文件),并在每次页面加载时将其写入同一个文件。
$filename = date('Y-m-d').".txt";
$fp = fopen($filename, "c+");
if (flock($fp, LOCK_EX)) {
$number = intval(fread($fp, filesize($filename)));
$number++;
ftruncate($fp, 0); // Clear the file
rewind($fp); // Move pointer to the beginning
fwrite($fp, $number); // Write incremented number
fflush($fp); // Write any buffered output
flock($fp, LOCK_UN); // Unlock the file
}
fclose($fp);发布于 2013-08-15 15:32:03
您可以使用此代码,这是一个简化的版本,但不确定它是否是最好的:
<?php
$fr = fopen("count.txt", "r");
$text = fread($fr, filesize("count.txt"));
$fw = fopen("count.txt", "w");
$text++;
fwrite($fw, $text);
?>https://stackoverflow.com/questions/18255780
复制相似问题