读书人

关于资料I/O 新手学C语言 请大神帮

发布时间: 2013-07-08 14:13:00 作者: rapoo

关于文件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;

}

为什么建立的文件一开始就输入了一个逗号呢???我是将数据输入到words里面 ,然后再写到文件当中的啊。。。新手不懂其中的缘故 请大神解答一下 3q
[解决办法]

#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;
}

[解决办法]
不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//...
if (条件2) continue;
//...
if (条件3) return;
//...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
whlie (!feof(f)) {
a=fgetc(f);
//...
b=fgetc(f);//可能此时已经feof了!
//...
}
而这样写就没有问题:
whlie (1) {
a=fgetc(f);
if (feof(f)) break;
//...
b=fgetc(f);
if (feof(f)) break;
//...
}
类似的例子还可以举很多。

读书人网 >C语言

热点推荐