C语言fscanf的一个问题

xingty xingty 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
下面程序是《C Primer Plus》上的一个例子。请问words数组在下面程序的作用是什么?我的理解是它是作为临时储存数据的,但是在程序中的第二个while循环中(即while (fscanf(fp,"%s",words) == 1)),不断从文件中读取数据储存到数组, 而数组最大只能容纳40个字符,但文件中的字符超过了40个,为什么还是能够正常输出?


#include <stdio.h>
#include <stdlib.h>
#define MAX 40

int main(void)
{
FILE *fp;
char words[MAX];
char ch ;
int len ;

if ((fp = fopen("wordy", "a+")) == NULL)
{
fprintf(stdout,"Can't open \"words\" file.\n");
exit(1);
}

puts("Enter words to add to the file; press the Enter");
puts("key at the beginning of a line to terminate.");
while (gets(words) != NULL && words[0] != '\0')
{
fprintf(fp, "%s ", words);
}

puts("File contents:");
rewind(fp);
while (fscanf(fp,"%s",words) == 1)
{
puts(words);
}

if (fclose(fp) != 0)
fprintf(stderr,"Error closing file\n");

return 0;
}
...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
xingty
C语言 70,039 成员 243,237 内容