为何这个程序非要用"w+"而另一个相似的程序却可以用"w"
为什么这个程序非要用"w+",而另一个相似的程序却可以用"w"
我写了两个练习fwrite与fread程序,一个非要用"w+",而另一个却可以用"w+"与"w"?。如下:
------解决方案--------------------
w模式是写模式,w+是读写模式
------解决方案--------------------
看一下MSDN就知道区别了,知道了区别也自然就有了答案
------解决方案--------------------
有没有+看你的需求
MSDN上详细的解释
------解决方案--------------------
我写了两个练习fwrite与fread程序,一个非要用"w+",而另一个却可以用"w+"与"w"?。如下:
#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main(void)
{
FILE *fp;
char str[100] = "abcbcfsafd";
char str2[50];
fp = fopen("f:\\789.txt", "w+"); //这里为什么非要用"w+",而下面的程序却可以用"w"?
if(fp == NULL)
{
fprintf(stdout, "Can not open the file.\n");
exit(1);
}
fwrite(str, strlen(str), 1, fp);
rewind(fp);
fread(str2, strlen(str), 1, fp);
str2[strlen(str)] = '\0';
fputs(str2, stdout);
fputs("\n", stdout);
fclose(fp);
return 0;
}
#include "stdafx.h"
#include "stdio.h"
int main()
{
FILE *fp;
int array[5] = {1, 5, 6, 4, 8};
fp = fopen("f:123.txt", "w"); //为什么这里可以用'w"
if(fp == NULL)
{
printf("Can not open the file.\n");
}
fwrite(array, sizeof(int), 5, fp);
rewind(fp);
fread(array, sizeof(int), 5, fp);
for(int i=0; i<5; i++)
{
printf("%d ", array[i]);
}
fclose(fp);
return 0;
}
------解决方案--------------------
w模式是写模式,w+是读写模式
------解决方案--------------------
看一下MSDN就知道区别了,知道了区别也自然就有了答案
------解决方案--------------------
有没有+看你的需求
MSDN上详细的解释
------解决方案--------------------
FOPEN(3) Linux Programmer's Manual FOPEN(3)
NAME
fopen, fdopen, freopen - stream open functions
SYNOPSIS
#include <stdio.h>
FILE *fopen(const char *path, const char *mode);
FILE *fdopen(int fd, const char *mode);
FILE *freopen(const char *path, const char *mode, FILE *stream);