《C语言及程序设计》实践参考——由键盘到文件

返回:贺老师课程教学链接  项目要求


【项目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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迂者-贺利坚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值