关于文件I/O 新手学C语言 请大神帮忙解答一下
#include <stdio.h>
#include <stdlib.h>
#define MAX 40
int main ()
{
FILE *fp;
char words[MAX];
char filename[MAX];
puts("Please input the filename you want to establish:");
scanf("%s",filename);
if ((fp=fopen(filename,"a+"))==NULL)
{
fprintf(stderr,"File open failed.\n");
exit(1);
}
printf("Please enter the the words you want to add to the file:%s\n",filename);
puts("To quit entering,press \'0\'!");
while(gets(words)!=NULL&&words[0]!='0')
fprintf(fp,"%s,",words);
if (fclose(fp)!=0)
{
fprintf(stderr,"Error in file closing!\n");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define MAX 40
int main ()
{
FILE *fp;
char words[MAX];
char filename[MAX];
puts("Please input the filename you want to establish:");
scanf("%s",filename);
if ((fp=fopen(filename,"w+"))==NULL)
{
fprintf(stderr,"File open failed.\n");
exit(1);
}
printf("Please enter the the words you want to add to the file:%s\n",filename);
puts("To quit entering,press \'0\'!");
//因为前边输入filename后还有一个换行符没读。。所以第一次gets读了这个换行符。。
//所以应该在gets前先把换行符读掉。。
while(getchar() != '\n');
while(gets(words)!=NULL&&words[0]!='0')
fprintf(fp,"%s,",words);
if (fclose(fp)!=0)
{
fprintf(stderr,"Error in file closing!\n");
}
return 0;
}