返回:贺老师课程教学链接 项目要求
【项目1-由键盘到文件】
(1)从键盘输入一个文件名,以及一个以#结束的字符序列,将输入的字符保存到文件中去。
#include "stdio.h" #include "stdlib.h" int main() { FILE *fp ; char ch,fname[10]; printf("文件名:"); gets(fname); if ((fp=____(1)____)==NULL) { printf("connot open\n"); exit(0); } while ((ch=getchar())!='#') fputc(____(2)____); ____(3)____; return 0; }[参考解答]
#include "stdio.h" #include "stdlib.h" int main() { FILE *fp ; char ch,fname[10]; printf("文件名:"); gets(fname); if ((fp=fopen(fname, "w"))==NULL) //(1) { printf("connot open\n"); exit(0); } while ((ch=getchar())!='#') fputc(ch,fp); //(2) fclose(fp); //(3) return 0; }
#include "stdio.h" #include "stdlib.h" int main() { FILE *fp1,*fp2 ; char c; if ((fp1=fopen("f1.dat", ___(1)___))==NULL) { printf("connot open\n"); exit(0); } if ((fp2=fopen("f2.dat", ___(2)___))==NULL) { printf("connot open\n"); exit(0); } c=fgetc(fp1); while (___(3)___) { fputc(c,fp2); c=fgetc(fp1); } ___(4)___ return 0; }[参考解答]
#include "stdio.h" #include "stdlib.h" int main() { FILE *fp1,*fp2 ; char c; if ((fp1=fopen("f1.dat", "r"))==NULL) //(1) { printf("connot open\n"); exit(0); } if ((fp2=fopen("f3.dat", "w"))==NULL) //(2) { printf("connot open\n"); exit(0); } c=fgetc(fp1); while (c!=EOF) //(3):或者!feof(fp1),feof函数用于检查是否到达文件尾 { fputc(c,fp2); c=fgetc(fp1); } fclose(fp2); fclose(fp1); //(4) return 0; }
#include "stdio.h" #include "stdlib.h" int main() { FILE ___(1)___; char ch; fp1=fopen("file1.dat","r"); fp2=fopen("file2.dat","w"); while (!feof(fp1)) { ch=___(2)___; putchar(ch); fputc(___(3)___); } fclose(fp1); fclose(fp2) ; return 0; }[参考解答]
#include "stdio.h" #include "stdlib.h" int main() { FILE *fp1, *fp2; //(1) char ch; fp1=fopen("file1.dat","r"); fp2=fopen("file2.dat","w"); while (!feof(fp1)) { ch=fgetc(fp1); //(2) putchar(ch); fputc(ch, fp2); //(3) } fclose(fp1); fclose(fp2) ; return 0; }