本文由 @lonelyrains 出品,转载请注明出处。 
文章链接: http://blog.csdn.net/lonelyrains/article/details/6637999


今天搜到一段关于linux下C语言获取系统时间的一段代码:

time_t now = time(0);
struct tm *tnow = localtime(&now);
printf("%d-%d-%d %d:%d:%d\n",1900+tnow->tm_year,
        tnow->tm_mon+1,
        tnow->tm_mday,
        tnow->tm_hour,
        tnow->tm_min,
        tnow->tm_sec);
首先说明一下,第二行代码,gcc编译器不允许直接tm *tnow的方式定义,而要以struct开头,否则提示未定义;g++却可以。然后我想包装成函数,方便以后用,结果为:
void vGetTime(struct tm *tnow)
{
    time_t now = time(0);
    tnow = localtime(&now);
    printf("%d-%d-%d %d:%d:%d\n",1900+tnow->tm_year,
        tnow->tm_mon+1,
        tnow->tm_mday,
        tnow->tm_hour,
        tnow->tm_min,
        tnow->tm_sec);
}
//调用时,先定义一个struct tm now的结构体变量,然后vGetTime(&now)方式调用。
而实际上,包装成函数后,改变的是tnow指针,返回到调用处的now时,已经改变了地址了。这个基础的错误,找了近个把小时。后来修改如下:
void vGetTime(struct tm *tnow)
{
    time_t now;
    struct tm *tmp;
    now = time(0);
    tmp = localtime(&now);
    tmp->tm_year += 1900;
    tmp->tm_mon  += 1;

    memcpy((void*)tnow,(const void *)tmp,sizeof(struct tm));
}
最后,需要包含的头文件有stdio.h、 time.h、 string.h(string.h是memcpy需要,不包含会警告,但不会报错)
Logo

更多推荐