io的第一天

题目一      使用fgets统计给定文件的行号

#include <myhead.h>
int main(int argc, const char *argv[])
{
    //判断传入的参数是否为2个
    if (argc != 2)
    {
        printf("input file error!!!\n");
        printf("usage:./a.out fileName\n");
        return -1;
    }
    //表示传过来的有一个文件
    //定义文件指针
    FILE *fp = NULL;
    if ((fp = fopen(argv[1], "r")) == NULL)
    {
        printf("fopen error\n");
        return -1;
    }

    char buf[128];
    int count = 0;
    while (fgets(buf, sizeof(buf), fp) != NULL)
    {
        count++;
    }
    printf("该文件内容的行数为:%d\n", count);
    // 关闭文件
    fclose(fp);
    return 0;
}

题目二      用fgets和fputs完成两个文件的拷贝

#include <myhead.h>
int main(int argc, const char *argv[])
{
    //判断传入的是否为三个文件
    if (argc != 3)
    {
        printf("input file error\n");
        printf("usage:./a.out srcfile destfile\n");
        return -1;
    }

    //以只读的形式打开源文件
    FILE *sfp = NULL;
    if ((sfp = fopen(argv[1], "r")) == NULL)
    {
        printf("open src file error\n");
        return -1;
    }

    //以只写的形式打开目标文件
    FILE *dfp = NULL;
    if ((dfp = fopen(argv[2], "w")) == NULL)
    {
        printf("open destfile error\n");
        return -1;
    }

    //开始copy逻辑
    //定义搬运工
    char buf[128];
    while (fgets(buf, sizeof(sfp), sfp) != NULL)
    {
        fputs(buf, dfp); //将读取的一行数据写入
    }
    printf("拷贝成功\n");

    fclose(sfp); //关闭俩文件
    fclose(dfp);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值