1

我正在尝试使用 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);

读取部分工作正常,如果文件被读取,则其内容被读取,即如果文件包含22892289则被读取。

问题是,当它增加并将值重写到该文件时,[NUL][NUL][NUL][NUL][NUL][NUL][NUL][NUL]1会被写入。

我错过了什么?为什么要写入空字符?

4

3 回答 3

5

您缺少的是rewind()。没有它,在截断为 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);
于 2015-03-11T20:56:11.160 回答
0

编辑#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');

?>
于 2013-08-15T15:28:49.780 回答
-1

您可以使用此代码,简化版本,但不确定它是否是最好的:

<?php
$fr = fopen("count.txt", "r");
$text = fread($fr, filesize("count.txt"));
$fw = fopen("count.txt", "w");
$text++;
fwrite($fw, $text);
?>
于 2013-08-15T15:32:03.853 回答