为什么 PHP 在一个文件中混合使用两个 fopen 句柄?

Why is PHP mixing two fopen handles on one file?

我在一个文件上测试两个 fopen() 句柄时注意到,句柄或通道混合在一起,并且当我调用 fread() 时文件内容为空。一个句柄是读,一个句柄是写。

示例代码:

$rh = fopen('existingfilewithcontent.txt', 'r');
$wh = fopen('existingfilewithcontent.txt', 'w');
echo fread($rh, 1000);
fclose($rh);
fclose($wh);
// file is now blank

这是在 Linux 和 Windows 上测试的。

我在 PHP 文档中找不到任何相关内容。

请不要问我为什么要在一个文件上使用两个句柄,因为这不是问题所在。

谢谢

打开文件进行写入具有破坏性。

手册说:

'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

你可能想要:

'r+' - Open for reading and writing; place the file pointer at the beginning of the file.

'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.

参见手册:http://php.net/manual/en/function.fopen.php