本文介绍了带有printf(“%d",astatbuff-> st_size)的C格式问题;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int lsdetails(struct stat *astatbuff) {
    printf("%d", astatbuff->st_size);
    printf("%d", astatbuff->st_atime);
    printf("%s\n", getpwuid(astatbuff->st_uid)->pw_name);

    return 0;
    }

我收到了以上错误消息,但我不明白为什么.我的印象是,我只为st_sizest_atime传递了一个参数.

I received the above error message but I do not understand why. I am under the impression that I am only passing one argument for both st_size and st_atime.

推荐答案

与C从0开始计数(数组元素:-)不同,gcc从1开始对函数参数进行计数.因此在printf (fmt, value)中,参数1"将引用fmt,而参数2"引用value.很简单,不是吗?

Unlike C, which starts counting at 0 (array elements :-), gcc starts counting function arguments at 1. So in printf (fmt, value), "argument 1" would refer to fmt, and "argument 2" refers to value. Easy, isn't it?

对于要打印__off_t的正确整数类型,当前没有100%保证和可移植的方式.最好的选择是将其转换为实现支持的最大无符号类型.请注意,unsigned long只能是32位宽,并且>> 4GB的文件会出现问题.如果您使用的是C99实施,或者它支持unsigned long long,则可以使用

As for the correct integer type to printf an __off_t, there currently is no 100% guaranteed and portable way. Your best bet is to cast it to the widest unsigned type your implementation supports. Note that an unsigned long may only be 32 bits wide and you'd get problems with files >= 4GB. If you have a C99 implementation, or if it supports unsigned long long, you should be fine with

printf("%llu", (unsigned long long)astatbuff->st_size);

当前POSIX标准化小组中正在进行讨论,以提供更多与其他POSIX类型(例如off_tpid_t等)相匹配的printf()格式说明符.文件大小将更便于携带和美观.

There are discussions in the current POSIX standardization group to provide more printf() format specifiers matching other POSIX types like off_t, pid_t etc. Once that is out the door (don't hold your breath), printing file sizes will be a little more portable and elegant.

这篇关于带有printf(“%d",astatbuff-> st_size)的C格式问题;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:59