IO进程线程作业

本文介绍了一个简单的时间记录程序,该程序将当前时间按指定格式写入到文本文件中,并在每次运行时延续之前的时间记录。此外,还提供了一个图片拷贝程序,用于将一张图片完整地复制到另一文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要求创建一个time.txt,存储内容格式如下:
[1] 2022-07-28 17:15:06
[2] 2022-07-28 17:15:07
[3] 2022-07-28 17:15:08
ctrl + c退出程序,过一会儿之后重新启动程序
[1] 2022-07-28 17:15:06
[2] 2022-07-28 17:15:07
[3] 2022-07-28 17:15:08 <-------------------
[4] 2022-07-28 17:16:31
[5] 2022-07-28 17:16:32
#include <head.h>

int main(int argc, char const *argv[])
{
    time_t t2;//long int t2
    char buf[10];//读取的长度
    FILE *fp, *lfp;//追加文件,读取文件
    int a = 1;

    if ((fp = fopen("./time.txt", "a")) == NULL)
        PRINT_ERR("open file error");
        //追加打开文件
    if ((lfp = fopen("./time.txt", "r")) == NULL)
        PRINT_ERR("open file error");
        //只读打开文件
        
    while (1)
    {
        time(&t2);//把秒数传给t2
        struct tm *info = NULL;//转换秒数为时间的函数
        info = localtime(&t2);

        fflush(fp);//刷新缓冲区
        while (fgets(buf, sizeof(buf), lfp) != NULL)//循环条件
        {
            if ((buf[strlen(buf) - 1]) == '\n')//判断行号
                a++;
        }

        fprintf(fp, "[%d] %d-%02d-%02d-%02d-%02d-%02d\n", a,//打印时间
                info->tm_year + 1900, info->tm_mon + 1, info->tm_mday,
                info->tm_hour, info->tm_min, info->tm_sec);
        sleep(1);
    }
    fclose(fp);
    fclose(lfp);

    return 0;
}

1.readwrite拷贝一张图片
#include <head.h>

int main(int argc, char const *argv[])
{
    int fd,lfd;//目标文件,源文件
    if((fd=open("./1.bmp",O_RDONLY))==-1)//只读方式打开
        PRINT_ERR("open file error");
    if((lfd=open("./1copy.bmp",O_WRONLY|O_TRUNC|O_CREAT,0666))==-1)
    //只写方式打开,文件不存在就创建,存在就清空,权限666(不加权限的话拷贝后的文件打不开)
        PRINT_ERR("open file error");

    char buf[128];
    int ret;//接收读取返回值,读取多少字节就返回多少
    while((ret=read(fd,buf,sizeof(buf)))>0)
        write(lfd,buf,ret);//不能使用sizeof(buf),因为可能会越界
    printf("拷贝成功\n");
    close(fd);
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值