c - 警告 : format '%06d' expects type 'int' , 但参数 5 的类型为 '__suseconds_t'

标签 c timeval

我正在使用这段代码:

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是)。只要 intlong 大小相同(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/

相关文章:

c++ - 获取给定日期对应于 ( local_timezone ) 午夜的 time_t/timeval

c - getrusage 是如何工作的以及 usage 结构内部到底是什么?

c++ - 将毫秒添加到 timeval C++

c - 输出重定向时 SIGINT 丢失;如何检测程序的终止?

c++ - C++ 文件中的 cuda 集成

c - 基于隐式矢量化的 HPC 编程语言

c++ - 在 C/C++ 中将月/日/年/时间转换为时间值

c - 是否可以#Include 到 "diamond inheritance"结构中?

C - 字符串值消失了吗?

c - 如何在 timeval 结构中从秒转换为纳秒?