【项目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; }
(2)设上题建立了名为f1.dat的文件,请将这个文件拷贝到一个名为f2.dat的文件中。
#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; }
(3)以下程序的功能是将文件file1.dat的内容输出到屏幕上并复制到文件file2.dat中,请补充完整。
#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; }
时间: 2024-10-10 11:36:44