如何在log文件中循环写入当地时间

  写一个简单的服务器需要记log,当然需要记下本地时间。关于时间的系列函数我还真一直没怎么注意,查了一下,可以通过time()来得到UTC,然后通过localtime转化为本地时间,最后通过strftime把localtime得到的结果按照你需要的格式化出来。写了demo实现每隔一秒钟往文件里面记录当地时间。后面需要的,就是在时间后面添加相应的动作记录。

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
#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 ;
}

 

转载于:https://www.cnblogs.com/python_newbie/archive/2010/08/08/1795300.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值