功能描述:程序运行时实时显示(1秒钟刷新一次),程序运行开始和结束时显示上一次运行结束时间;程序结束时将结束时间写入日志文件中【即程序记录开始时间和结束时间】;
file.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#define TIME_STR_MAX_LEN 20
#define TIME_LOOP_SECONDS 10 * 1
#define TIME_DATA_FILE "time_data.txt"
typedef struct _time_struct {
int year;
int month;
int day;
int hour;
int min;
int second;
int isdst;
}TimeStruct;
TimeStruct GetCurrentTime();
int main()
{
int timeFd = open(TIME_DATA_FILE, O_RDWR | O_CREAT);
char curTimeStr[TIME_STR_MAX_LEN] = {
0};
TimeStruct curTime;
int ret = lseek(timeFd,0, SEEK_END);
if(ret == -1) {
perror("lseek error.");
return -1;
} else if(ret == 0) {
curTime = GetCurrentTime();
sprintf(curTimeStr, "%d-%d-%d %d:%d:%d\n", curTime.year, curTime.month, curTime.day,
curTime.hour, curTime.min, curTime.second);
printf("process run first time at:%s.\n", curTimeStr);
} else {
ret = lseek(timeFd,-(sizeof(curTimeStr)), SEEK_END);
read(timeFd, curTimeStr, sizeof(curTimeStr));
printf("last time process end at:%s.\n", curTimeStr);
}
ret = write(timeFd, curTimeStr, sizeof(curTimeStr));
if(ret == -1) {
perror("write error.");
return -1;
}
int loopSeonds = 0;
while(loopSeonds < TIME_LOOP_SECONDS){
curTime = GetCurrentTime();
sprintf(curTimeStr, "%d-%d-%d %d:%d:%d\n", curTime.year, curTime.month, curTime.day,
curTime.hour, curTime.min, curTime.second);
printf("%s", curTimeStr);
sleep(1);
loopSeonds++;
}
ret = write(timeFd, curTimeStr, sizeof(curTimeStr));
if(ret == -1) {
perror("write error.");
return -1;
}
close(timeFd);
printf("file operation completed.\n");
return 0;
}
TimeStruct GetCurrentTime()
{
time_t tempTime;
struct tm *curTime;
time(&tempTime);
curTime = gmtime(&tempTime);
TimeStruct destTime;
destTime.year = curTime->tm_year + 1900;
destTime.month = curTime->tm_mon + 1;
destTime.day = curTime->tm_mday;
destTime.hour = curTime->tm_hour + 8;
destTime.min = curTime->tm_min;
destTime.second = curTime->tm_sec;
destTime.isdst = curTime->tm_isdst;
return destTime;
}