Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between r+ and w+ in fopen()

Tags:

c

fopen

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?

like image 819
yaylitzis Avatar asked Jan 14 '14 12:01

yaylitzis


People also ask

What is the difference between R and W mode?

r+: Opens a file in read and write mode. File pointer starts at the beginning of the file. w+: Opens a file in read and write mode. It creates a new file if it does not exist, if it exists, it erases the contents of the file and the file pointer starts from the beginning.

What does W mean in fopen?

"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).

What does R mean in fopen?

r+ mode. Purpose. Opens an existing text file for reading purpose. Opens a text file for both reading and writing. fopen Returns if FILE doesn't exists.

What is the difference between W and W+ in C?

Originally Answered: Where is the difference between in 'w' and 'w+' mode of fopen() in PHP or C? fopen with w letter denotes that text is appended to the end of the file, while w+ deletes the content of the file and starts writing new content into the file.


2 Answers

Both r+ and w+ 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, whereas w+ deletes the content of the file and creates it if it doesn't exist.

like image 68
Peter Avatar answered Sep 22 '22 21:09

Peter


The main difference is w+ truncate the file to zero length if it exists or create a new file if it doesn't. While r+ neither deletes the content nor create a new file if it doesn't exist.

Try these codes and you will understand:

#include <stdio.h> int main() {    FILE *fp;     fp = fopen("test.txt", "w+");    fprintf(fp, "This is testing for fprintf...\n");    fputs("This is testing for fputs...\n", fp);    fclose(fp); }   

and then this

#include <stdio.h> int main() {    FILE *fp;     fp = fopen("test.txt", "w+");    fclose(fp); }    

If you will open test.txt, you will see that all data written by the first program has been erased.
Repeat this for r+ and see the result.
Here is the summary of different file modes (1 => ture, 0 => false):

enter image description here

like image 26
haccks Avatar answered Sep 24 '22 21:09

haccks