【问题标题】:How do you print utmp struct's data in utmp.h?如何在 utmp.h 中打印 utmp 结构的数据?
【发布时间】:2021-12-09 23:26:34
【问题描述】:

我想学习使用 utmp.h 附带的函数和数据结构。 在下面的代码中,我想遍历 utmp 结构并打印它们的数据字段。

#include <stdio.h>
#include <utmp.h>

int main()
{
        struct utmp *data;
        data = getutent();
        int i = 0 ;
        while(data != NULL)
        {
                ++i;
                printf("%s\n" , data->ut_id);
                data = getutent();
        }
        printf("%d" , i);
        return 0 ;
}

即使ut_idchar[4] 类型,当我运行代码时,我也会收到以下警告:

警告:“__builtin_puts”参数 1 声明的属性“非字符串”[-Wstringop-overflow=]

我该如何解决?

【问题讨论】:

  • 该字段可能不适用于以 0 结尾的 C 字符串,并且不应与期望为 0 的函数一起使用。

标签: c unix compiler-warnings gcc-warning


【解决方案1】:

此警告是 gcc 特定属性 __attribute_nonstring__ 的结果,该属性用于指示字符数组不一定以 NUL 字符结尾,因此与标准库字符串函数。 Linux 中的utmp 结构在其字符数组字段中使用该属性定义。

要解决该警告,您可以使用 printf() 修饰符 %.*s 指定字符数组的固定宽度输出,如下所示:

printf("%.*s\n" , (int)(sizeof data->ut_id), data->ut_id);

(您可以只使用4 作为第二个参数,但sizeof 更灵活)。

【讨论】:

  • 非常感谢,您解释得很好。这是我第一次遇到 attribute_nonstring 。所以如果其他人有这个问题,utmp 结构的某些字段有 attribute_nonstring
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多