fseek($file, SEEK_END) + fwrite() 写入文件开头而不是结尾

Jea*_*esi 2 php io json fwrite

我正在尝试将一个字符串附加到一个包含 json 字符串的文件中。为此,我必须删除最后一个括号“]”,并将新字符串附加到文件末尾。这就是我尝试这样做的方式:

$fh = fopen($target_file, 'r+') or die("can't open file");  // opens file
$stat = fstat($fh);                                         // get data from statt struct
ftruncate($fh, $stat['size']-1);                            // remove last char
fseek($fh, SEEK_END);                                       // move file pointer to end
fwrite($fh, $append_str);                                   // write new string
fclose($fh);                                                // close
Run Code Online (Sandbox Code Playgroud)

但是, $append_str 被写入文件的开头。附加操作的工作应该有什么不同?(ps:使用wamp服务器)

小智 5

只需使用 a+,它将在文件末尾设置文件指针。