Difference between r+ and w+ in fopen()

2019-01-16 04:57发布

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?

标签: c fopen
5条回答
The star\"
2楼-- · 2019-01-16 05:26

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);
}   

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.

查看更多
爷的心禁止访问
3楼-- · 2019-01-16 05:26

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.

查看更多
4楼-- · 2019-01-16 05:31

r+ The existing file is opened to the beginning for both reading and writing. w+ Same as w except both for reading and writing.

查看更多
来,给爷笑一个
5楼-- · 2019-01-16 05:35
r = read mode only
r+ = read/write mode
w = write mode only
w+ = read/write mode, if the file already exists override it (empty it)

So yes, if the file already exists w+ will erase the file and give you an empty file.

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-16 05:36

There are 2 differences, unlike r+, w+ will:

  • create the file if it does not already exist
  • first truncate it, i.e., will delete its contents
查看更多
登录 后发表回答