我有一个类型的变量size_t,我想用它打印printf().我使用什么格式说明符来便携地打印它?
在32位机器上,%u似乎是对的.我编译了g++ -g -W -Wall -Werror -ansi -pedantic,并没有警告.但是当我在64位机器中编译该代码时,它会产生警告.
size_t x = <something>;
printf( "size = %u\n", x );
warning: format '%u' expects type 'unsigned int',
but argument 2 has type 'long unsigned int'
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,警告会消失,如果我将其更改为%lu.
问题是,如何编写代码,以便在32位和64位机器上编译警告?
编辑:作为一种解决方法,我想一个答案可能是将变量"转换"为一个足够大的整数,比如说unsigned long,并使用打印%lu.这在两种情况下都有效.我在寻找是否还有其他想法.
在我的程序中,我统计他们想要的文件并发送数据.stat的字段struct都是特殊类型:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number …Run Code Online (Sandbox Code Playgroud)