如何在log文件中循环写入当地时间
写一个简单的服务器需要记log,当然需要记下本地时间。关于时间的系列函数我还真一直没怎么注意,查了一下,可以通过time()来得到UTC,然后通过localtime转化为本地时间,最后通过strftime把localtime得到的结果按照你需要的格式化出来。写了demo实现每隔一秒钟往文件里面记录当地时间。后面需要的,就是在时间后面添加相应的动作记录。
代码
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUF_SIZE 256
#define FILE_NAME "log.txt"
static void getTime(char *timeBuffer)
{
time_t timeVal;
struct tm *pTime;
time(&timeVal);
pTime = localtime(&timeVal);
strftime(timeBuffer, BUF_SIZE, "%Y-%m-%d %H:%M:%S\n", pTime);
return;
}
static void writeLog(const char *timeBuffer)
{
int fd = open(FILE_NAME, O_RDWR | O_CREAT | O_APPEND, S_IRWXU);
write(fd, timeBuffer, strlen(timeBuffer));
close(fd);
return;
}
int main(int argc, char *argv[])
{
char timeBuffer[BUF_SIZE] = {0x00};
while (1)
{
getTime(timeBuffer);
writeLog(timeBuffer);
sleep(1);
}
return 0;
}


浙公网安备 33010602011771号