In fopen("myfile", "r+")
what is the difference between the "r+"
and "w+"
open mode? I read this:
"r"
Open a text file for reading."w"
Open a text file for writing, truncating an an existing file to zero length, or creating the file if it does not exist.
"r+"
Open a text file for update (that is, for both reading and writing)."w+"
Open a text file for update (reading and writing), first truncating the file to zero length if it exists or creating the file if it does not exist.
I mean the difference is that if I open the file with "w+"
, the file will be erased first?
Try these codes and you will understand:
and then this
Then open the file
test.txt
and see the what happens. You will see that all data written by the first program has been erased.Repeat this for
r+
and see the result. Hope you will understand.Both
r+
andw+
can read and write to a file. However,r+
doesn't delete the content of the file and doesn't create a new file if such file doesn't exist, whereasw+
deletes the content of the file and creates it if it doesn't exist.r+ The existing file is opened to the beginning for both reading and writing. w+ Same as w except both for reading and writing.
So yes, if the file already exists w+ will erase the file and give you an empty file.
There are 2 differences, unlike
r+
,w+
will: