关于io的一些操作

1.写一个日志文件,将程序启动后,每一秒的时间写入到文件中

#include <myhead.h>
#include <unistd.h>

int main()
{
    //定义文件指针
    FILE *fp = NULL;
    if ((fp = fopen("./time.txt", "w")) == NULL)
    {
        //strerror:将错误吗转变为错误信息
        printf("errno:%s\n", strerror(errno));
        return -1;
    }
    int count = 0;
    while (count != 10)
    {
        //定义变量储存描述
        time_t sys_time = time(NULL);
        //将秒数转换为结构体
        struct tm *time_ptr = localtime(&sys_time);

        char buf[128] = "";
        snprintf(buf, sizeof(buf), "%4d-%2d-%2d %2d:%2d:%2d\n",
                 time_ptr->tm_year + 1900,
                 time_ptr->tm_mon + 1,
                 time_ptr->tm_mday,
                 time_ptr->tm_hour,
                 time_ptr->tm_min,
                 time_ptr->tm_sec);

        printf("buf=%s\n", buf);
        fwrite(buf, strlen(buf), 1, fp); //单字符吸入
        count++;
        sleep(1);
    }
    fclose(fp);
    return 0;
}

2.使用fread、fwrite完成两个文件的拷贝

#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;
    }

    // 读取文件内容
    char buf[128];
    int res;
    while ((res = fread(buf, 1, sizeof(buf), sfp)) > 0) // 检查res是否大于0
    {
        fwrite(buf, 1, res, dfp);
    }

    fclose(sfp);
    fclose(dfp);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值