2

我必须编写一个sleep(60)在无限循环中调用的程序。通过循环每五次我必须获取当前时间并打印 tm_sec 字段。

这是我写的:

#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>

int main()
{
    struct tm t1;
    int i=0;
    for(;;)
    {
        sleep(60);
        if(i%5==0)
            {
                gettimeofday(&t1,NULL);
                printf("%d\n",t1.tm_sec);
            }
        i++;
    }
}

我收到一条错误消息aggregate tm t1 has incomplete type and cannot be defined.

我不知道我做错了什么。

4

3 回答 3

3

你想要 struct timeval,而不是 struct tm。尝试这个:

struct timeval t1;

另外,你想要t1.tv_sec,不是t1.tm_sec

于 2011-11-29T04:10:15.720 回答
2

你用错了。选择以下两项之一:

#include <sys/time.h>

int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);

或者:

 #include <time.h>

 char *asctime(const struct tm *tm);
 struct tm *gmtime(const time_t *timep);
 struct tm *localtime(const time_t *timep);
于 2011-11-29T04:12:19.540 回答
1

gettimeofday接受一个指向timeval, not的指针tm,给出自 1970 年以来的秒数(和微秒数)。

如果您想要一个tm,那么您将需要 中的函数<ctime>,例如localtime()转换 的秒字段timeval

于 2011-11-29T04:11:28.357 回答