如何使用 printf 系列可移植地打印 size_t 变量? #让代码影响世界

本篇将介绍在C/C++编码中如何用printf打印size_t/ssize_t这类变量类型,最常用到的就是c语言中的size操作,还有C++中的vector::size(),以及其它 STL 容器的 size()也是如此。

 C语言例子:

int main(void)
{
    int fd1 = open("test.txt", O_RDONLY); // 只读模式打开文件
    if (fd1 == -1) {
        perror("open test.txt");
        exit(1);
    }

    char buf[1024] = {0};
    ssize_t r_count = read(fd1, buf, sizeof(buf));
    if (r_count == -1) {
        perror("read fd1");
        exit(1);
    }
    printf("read bytes = %d\n", r_count); // 读取成功返回读取的字节数

    close(fd1);
    return 0;
}

编译后会出现一个编译警告

   warning: format '%d' expects type 'signed int', but argument 2 has type 'long signed int'

原因在于:系统调用的返回值为ssize_t

    #include <unistd.h> ssize_t read(int fs, void *buf, size_t N);

32位系统上述代码没有问题,但64位系统,或者兼容32/64位系统,则须要采用z modifier的方法。

正确方法是参考如下使用zu\zx\zd格式化字符串:

size_t x = ...;
ssize_t y = ...;
printf("%zu\n", x);  // prints as unsigned decimal
printf("%zx\n", x);  // prints as hex
printf("%zd\n", y);  // prints as signed decimal

C++例子:用 printf 打印 vector 的 size,如下例代码,

// g++ cpp-printf-size_t.cpp -o a.out -std=c++11
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5};
    printf("size=%d", v.size());
}

来自 <C/C++ printf 列印 size_t 的方法 | ShengYu Talk>

编译后会出现一个编译警告:

cpp-printf-size_t.cpp:8:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘std::vector<int>::size_type {aka long unsigned int}’ [-Wformat=]

printf("size=%d", v.size());

来自 <https://www.ibm.com/docs/en/zos/2.3.0?topic=functions-read-read-from-file-socket>

改为zu则可合理解决该问题。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值