想要“hello!”赋给str[]数组,然后输出,结果输出来的全是null,求解为什么?

#include <stdio.h> 
main()
{ FILE *fp;
char *p;
int i=0;
char str[10];
fp=fopen("C:\\Users\\Administrator\\Desktop\\c程序设计\\text.txt","w");
fputs("hello!",fp);
fp=fopen("C:\\Users\\Administrator\\Desktop\\c程序设计\\text.txt","r");
fgets(str,5,fp);
for(i;i<10;i++)
printf("str=%s",str[i]);
getchar();

}

繁星淼淼
浏览 106回答 2
2回答

阿晨1998

fopen连续执行两次,第二次open的文件是空的。第一次先close一下再open。

慕标琳琳

#include&nbsp;<stdio.h>&nbsp;int&nbsp;main(void){FILE&nbsp;*fp;&nbsp;&nbsp;&nbsp;&nbsp;char&nbsp;str[10]={0};&nbsp;&nbsp;&nbsp;&nbsp;if((fp=fopen("D:/123/text.txt","w+"))==NULL)//&nbsp;文件必须已经存在{printf("ERROR!\n");exit(1);}&nbsp;&nbsp;&nbsp;&nbsp;fputs("hello!",fp);fseek(fp,0,SEEK_SET);&nbsp;//&nbsp;把当前指针移到文件开始处fgets(str,7,fp);&nbsp;&nbsp;&nbsp;&nbsp;printf("str=%s",str);fclose(fp);return&nbsp;0;}
打开App,查看更多内容
随时随地看视频慕课网APP