w+
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
rewind(fp);
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
输出
This is testing for fprintf...
test.txt
This is testing for fprintf...
使用w和r来组成w+
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w");
fprintf(fp, "This is testing for fprintf...\n");
fclose(fp);
fp = fopen("test.txt", "r");
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
输出
This is testing for fprintf...
test.txt
This is testing for fprintf...
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);
rewind(fp);
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
输出
This is testing for fprintf...
test.txt
This is testing for fprintf again...
r 和 w 合并成 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;
}
输出
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+");
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
rewind(fp);
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
输出
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...
使用 a 和 r 来形成 a+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "a");
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;
}
输出
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...
w+
模式打开文件,它将首先被“擦除”,或者在不存在时创建它(而r+
模式在这种情况下会出错)。 - ShinTakezou