填空题 请补充main()函数,该函数的功能是:把文本文件text2中的内容追加到文本文件text1的内容之后。
例如,文件text2的内容为“I"m very happy!”,文件text1的内容为“I"m a girl,”,追加之后文件text1的内容为“I"m a girl, I"m very happy”。
注意:部分源程序给出如下。
请勿改动main()函数和其他函数中的任何内容,仅在函数main()的横线上填入所编写的若干表达式或语句。
试题程序:
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
#define M 80
void main()
{
FILE*fp, *fp1, *fp2;
int i;
char c[M], ch;
system("CLS");
if((fp=fopen("text1.dat", "r"))==NULL)
{
printf("file text1 cannot be opened/n");
exit(0);
}
printf("/n text1 contents are: /n/n");
for(i=0; (ch=fgetc(fp))!=EOF; i++)
{
c[i]=ch;
putchar(c[i]);
}
fclose(fp);
if((fp=fopen("text2.dat", "r"))==NULL)
{
printf("file text2 cannot be opened/n");
exit(0);
}
printf("/n/n/nB contents are: /n/n");
for(i=0; (ch=fgetc(fp))!=EOF; i++)
{
d[i]=ch;
putchar(c[i]);
}
fclose(fp);
if((fp1=fopen("text1.dat", "a")) 1 (fp2=fopen("text2.dat", "r")))
{
while((ch=fgetc(fp2))!=EOF)
2;
}
else
{
printf("Can not open text1 text2!/n");
}
fclose(fp2);
fclose(fp1);
printf("/n***new text1 contents***/n/n");
if((fp=fopen("text1.dat", "r"))==NULL)
{
printf("file text1 cannot be opened/n"):
exit(0);
}
for(i=0; (ch=fgetc(fp))!=EOF; i++)
{
c[i]=ch;
putchar(c[i]);
}
3;
}
【正确答案】
【答案解析】&& fputc(ch, fp1) fclose(fp)[解析] 要让文件text2中的内容追加到文件text1的内容之后,两个文件都要存在,因此第一处填“&&”;如果两个文件均存在,则把文件text2中的每一个字符追加到文件text1的内容之后,因此第二处填“fputc(ch, fp1)”;每打开一个文件,当文件不再使用时要将该文件关闭,因此第三处填“fclose(fp)”。