Many answers here in Stack Overflow use fopen($file, "rw+")
, but the manual doesn't list the "rw+"
mode, there's only the "r+"
mode (or "w+"
mode).
So I was wondering, what does the "rw+"
mode do? What's the difference between fopen($file,
"rw+"
or "r+"
? I'm asking this because there is no documentation on the "rw+"
mode.
One approach is to consider that the modes are additive, but I couldn't find any mention of combining modes in the fopen
manual page (besides, what's the sense of combining "r"
with "w+"
, if "w+"
already makes it readable?). But most importantly, w+
mode truncates the file, while rw+
does not truncate it (therefore, they cannot be additive). Probably there is no rw+
mode, despite its use by Stack Overflow users. Maybe it works because the parser ignores the "w" letter, as the rw+
mode appears to be === r+
?
To clarify my question: what is the "rw+"
mode, that is, how does it differ from other modes? I only received two answers in the comments: either that I should check the documentation (I already checked and rechecked) and a wrong answer, which said it is equal to "w+"
(it isn't). "w+"
truncates the file, while "rw+"
doesn't.
Here's a script for testing (it proves that w+
truncates the file, but rw+
doesn't):
<?php
$file = "somefile";
$fileOpened = fopen($file, "w");
fwrite($fileOpened, "0000000000000000000");
fclose($fileOpened);
$fileOpened = fopen($file, "rw+");
fwrite($fileOpened, "data");
fclose($fileOpened);
$fileOpened = fopen($file, "r");
$output = fgets($fileOpened);
echo "First, with 'rw+' mode:<br>".$output;
$fileOpened = fopen($file, "w+");
fwrite($fileOpened, "data");
fclose($fileOpened);
$fileOpened = fopen($file, "r");
$output = fgets($fileOpened);
echo "<br><br><br>Now with only 'w+' mode:<br>".$output;
?>