我正在使用这段代码:
struct timeval tv;
time_t nowtime;
struct tm *nowtm;
char tmbuf[64], buf[64];
gettimeofday(&tv, NULL);
nowtime = tv.tv_sec;
nowtm = localtime(&nowtime);
strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", nowtm);
snprintf(buf, sizeof buf, "%s.%06d", tmbuf, tv.tv_usec);
来自这个 SO 答案:
https://stackoverflow.com/a/2409054/997112
以可读格式打印 struct timeval。但是,我收到此编译器警告:
warning: format '%06d' expects type 'int', but argument 5 has type '__suseconds_t'
有人可以帮忙吗?
最佳答案
编译器发出警告,因为 printf 期望的类型 - int
与参数 - long
的类型不同(__suseconds_t
是)。只要 int
和 long
大小相同(32 位或 64 位),您的代码就可以在许多当前系统上运行。
因为有 系统不是这种情况(例如 int 32 位,long 64 位),为了更好的可移植性,您应该将值转换为实际类型 printf
期望:
snprintf(buf, sizeof buf, "%s.%06ld", tmbuf, (long) tv.tv_usec);
由于 tv.tv_usec
的值总是小于一百万,在至少有 32 位整数的系统上,"%06d"
和转换为 int 将也可以,但我更愿意长期使用。
顺便说一句,警告指出了这些天使用的所有类型定义的问题。我认为,如果消息中提到 long
而不是 __suseconds_t
或除此之外,相对初学者可能有更好的机会理解实际问题。 clang 编译器实际上是这样做的:"'__suseconds_t' (aka 'long')"
。
关于c - 警告 : format '%06d' expects type 'int' , 但参数 5 的类型为 '__suseconds_t',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24486615/