服务器log日志demo

任务描述:每次开启任务向文件中写入此时时间,下一次开启的时候从文件末尾追加记录


#include <stdio.h>
#include <time.h>
#include <sys/types.h>  
#include <sys/stat.h>  
#include <fcntl.h>  
#include<stdlib.h>  
#include<unistd.h>  
#include<string.h> 

#define FILE_NAME "test.log"

/**
*  获取时间
**/
struct tm  * time_get_all()
{
    time_t now ;
    struct tm *tm_now ;
    time(&now) ;
    tm_now = localtime(&now) ;

    return tm_now;
}

/**
* 判断文件是否存在
**/
int judge_file_state()
{
    const char *file_name = FILE_NAME; 
    if(access(FILE_NAME,F_OK)==0)
    {
        //file exists
        file_exists_inexistence(1);
    }
    else{
        //file inexistence 
        file_exists_inexistence(2);
    }
    return 0;
}



/**
* 文件存在传值2 不存在传值1
**/
int file_exists_inexistence(int arg)
{
    const char *file_name = FILE_NAME;
    int fd = 0;   
    char buf[1024]= " ";  
    struct tm *tm_now;

    if(arg == 2){
        fd=open(file_name,O_CREAT|O_RDWR,0644);
        printf("file  inexistence \n");
    }
    else if(arg == 1){
        fd=open(file_name,O_APPEND|O_RDWR,0644);
        lseek( fd, 0, SEEK_SET );
        printf("file exists \n");
    }

    for(;;){
        tm_now =time_get_all();
        sprintf(buf,"[%d-%d-%d] %d:%d:%d\n",tm_now->tm_year+1900, tm_now->tm_mon+1, tm_now->tm_mday, tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec);
        write(fd,buf,strlen(buf));          
        sleep(1);
    }

    close(fd);    
    return 0;
}


int main(int argc,char *argv[])  
{  
    judge_file_state();
    return 0;  

} 

编译文件,然后运行
下面是打印的log

[2018-6-19] 1:44:28
[2018-6-19] 1:44:29
[2018-6-19] 1:44:30
[2018-6-19] 1:44:31
[2018-6-19] 1:44:32
[2018-6-19] 1:44:33
[2018-6-19] 1:44:34
[2018-6-19] 1:44:35
[2018-6-19] 1:46:8
[2018-6-19] 1:46:9
[2018-6-19] 1:46:10
[2018-6-19] 1:46:11
[2018-6-19] 1:46:12
[2018-6-19] 1:46:13
[2018-6-19] 1:46:14
[2018-6-19] 1:46:15
[2018-6-19] 1:46:16

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_小白鱼儿_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值