任务描述:每次开启任务向文件中写入此时时间,下一次开启的时候从文件末尾追加记录
#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