IO线程,day2

该代码示例包含两个部分:1)使用snprintf,time,localtime函数每秒更新时间并写入文件,避免重复写入相同秒数。2)通过fread和fwrite函数实现字符串从源文件到目标文件的拷贝。

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

 作业:

1,完成时间自动更新(snprintf,fread,time,localtime)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
int main(int argc, char const *argv[])
{
    FILE *fp;//一会用来把时间放到文件中
    if((fp=fopen("./time.txt","w"))==NULL)
    {
        perror("open file");
        return -1;
    }

    char oldtime[50];//定义一个旧的时间数组
    char newtime[50];//定义一个新的时间数组

    int count=0;//用来计数,目前就看到几个结果就行了

    //循环时间
    while(1)
    {
    //获取系统时间毫秒数
    time_t  sys_time=time(NULL);
    //把系统毫秒数转换为结构体指针
    struct tm *nowtime=localtime(&sys_time);
    //把结构体指针转换成字符串
    sprintf(newtime,"%4d-%2d-%2d %2d:%2d:%2d\n",nowtime->tm_year+1900,nowtime->tm_mon,
    nowtime->tm_mday,nowtime->tm_hour,nowtime->tm_min,nowtime->tm_sec);

    //比较新旧时间是否相等,一秒内程序可能跑好多次,一秒内可能在文件里面看到好多次相等的秒数
    if((strcmp(newtime,oldtime)!=0))
     {
        fputs(newtime,fp);//把时间写入到文件中,不用fwrite是因为他存到里面是ascill值,有乱码
        printf("%s\n",newtime);
        strcpy(oldtime,newtime);
        count++;
     }
     if(count==10)break;
    }
    return 0;
}

 2.用fread和fwrite实现字符串拷贝

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
int main(int argc, char const *argv[])
{
    //判断输入文件的个数,包括拷贝的源文件于目标文件
    while(argc!=3)
    {
        printf("file count error\n");
        printf("usage:./a.out str dest\n");
        return -1;
    }

    FILE *str;
    FILE *dest;

    if((str=fopen(argv[1],"r"))==NULL)
    {
        perror("open file");
        return -1;
    }

        if((dest=fopen(argv[2],"w"))==NULL)
    {
        perror("open file");
        return -1;
    }

    char s[500];

    fread(s,1,sizeof(s),str);
    //把文件中的数据放到数组中

    fwrite(s,1,sizeof(s),dest);
    //把数组中的数据拷贝到新的文件中

    printf("%s\n",s);

    fclose(str);
    fclose(dest);
    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值