2011-11-20 96 views
1

我试图以十进制精度在ISO-8601中打印时间。 YYYY-MM-DDTHH:MM:SS.SC:gettimeofday()每次运行产生相同的值

这里是我的代码:

#include <sys/time.h> 
#include <time.h> 
#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 

void milli_time(char* dest, struct timeval* t) 
{ 
    struct tm* timeInfo; 
    strftime(dest, 22, "%Y-%m-%dT%t", localtime(&t->tv_sec)); 
    printf("%s\n", dest); 
    fflush(stdout); 
    char deciTime[3]; 
    sprintf(deciTime, ".%lu", ((t->tv_usec)/100000ul)); 

    strcat(dest, deciTime); 
} 

int main() 
{ 
    struct timeval* theTime; 
    char timeString[32]; 
    gettimeofday(theTime, NULL); 
    printf("%lu.%lu\n", theTime->tv_sec, theTime->tv_usec); 
    milli_time(timeString, theTime); 
    printf("%s\n", timeString); 
    fflush(stdout); 
} 

和输出我每次运行它是:

134520616.3077826840 
1974-04-06T17:50:16 
1974-04-06T17:50:16.30778 

其他的事情,我注意到是tv_usec大于一百万。

回答

5

变化struct timeval* theTimestruct timeval theTime和更新它的相应的引用:

gettimeofday(&theTime, NULL); 
// etc 

这样你分配的空间的结构,而不仅仅是一个指针结构。当我尝试在我的机器上运行代码时,您的代码会出现段错误。

+0

这工作,非常感谢。 – julianc

相关问题