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

  • Post author:
  • Post category:其他




本篇将介绍在C/C++编码中如何用


p


rintf打印size_t


/s


size_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则可合理解决该问题。



版权声明:本文为vdigital原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。