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);
}
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:
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.
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w+"); //write and read mode
fprintf(fp, "This is testing for fprintf...\n");
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r+"); //read and write mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf again...
r and w to form r+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r");
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
fp=fopen("test.txt","w");
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf again...
a+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "a+"); //append and read mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...
a and r to form a+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "a"); //append and read mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
fp=fopen("test.txt","r");
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...