问题描述
在fopen("myfile", "r+")
中,"r+"
和"w+"
打开模式有什么区别?我读到了:
In fopen("myfile", "r+")
what is the difference between the "r+"
and "w+"
open mode? I read this:
"r+"
打开一个文本文件进行更新(即,用于读取和读取). 写作).
"w+"
打开一个文本文件进行更新(读取和写入), 首先截断 如果文件存在,则文件长度为零;如果文件不存在,则文件长度为零.
"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.
我的意思是区别在于,如果我使用"w+"
打开文件,该文件将首先被删除吗?
I mean the difference is that if I open the file with "w+"
, the file will be erased first?
推荐答案
主要区别在于w+
如果文件存在,则将文件截短为零长度;如果不存在,则创建一个新文件.而r+
既不删除内容也不创建新文件(如果不存在).
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);
}
然后是
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w+");
fclose(fp);
}
然后打开文件test.txt
,然后查看会发生什么.您将看到第一个程序写入的所有数据已被删除.
对r+
重复此操作并查看结果.希望你能理解.
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.
这篇关于fopen()中r +和w +之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!