可能重复:
How should I print types like off_t and size_t?
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int fd, offset;
char *data;
struct stat sbuf;
int counter;
if (argc != 2)
{
fprintf(stderr, "usage: mmapdemo offset\n");
exit(1);
}
if ((fd = open("mmapdemo.c", O_RDONLY)) == -1)
{
perror("open");
exit(1);
}
offset = atoi(argv[1]);
if (offset < 0 || offset > sbuf.st_size-1)
{
fprintf(stderr, "mmapdemo: offset must be in the range 0 - %d \n",
sbuf.st_size-1);
exit(1);
}
data = mmap((caddr_t)0, sbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (data == (caddr_t)(-1))
{
perror("mmap");
exit(1);
}
// print the while file byte by byte
while(counter++<=sbuf.st_size)
printf("%c", *data++);
return 0;
}当我运行这段代码时,它给我的错误是
gcc mmap.c -o mmap mmap.c:在函数'main':mmap.c:38:警告:格式'%d‘期望类型' int’,但参数3的类型是'long int‘
请告诉我,为什么会这样?
发布于 2010-11-06 05:04:06
我相信你漏掉了密码。
但是,在您的printf语句中,您使用的是%d标志,但是in需要使用%ld。
编辑:
这是一个bug:
fprintf(stderr, "mmapdemo: offset must be in the range 0 - %d \n",
sbuf.st_size-1);应:
fprintf(stderr, "mmapdemo: offset must be in the range 0 - %ld \n",
sbuf.st_size-1);发布于 2010-11-06 05:03:35
你的代码没有正确显示。您所得到的错误只是一个警告。这意味着您使用了错误的格式字符串。对于长int,您可能应该使用%ld。
发布于 2010-11-06 05:04:27
使用%ld
嗯,你发布的片段看起来不像里面有38行,但是你引用的错误来自于使用%d格式而不是%ld或者它的相关C99符号格式之一。
好的,现在有更多的代码张贴。虽然st_size在技术上是off_t,而且没有off_t的C99格式说明符,但%zd将打印size_t并符合C99。这可能是你最好的了。
然而,作为一个实际问题,%ld也将工作,是一个可以接受的选择。
更新:好的,我给您提供了关于编译程序的建议,但是指出,一个可移植的程序至少应该在ILP32、LP64和LLP64上运行,所以在这种情况下,有必要将格式转换为任何类型,如果您想让所有64位都在所有这些系统上实际打印,那么唯一的选择是%lld和对(long long)的强制转换。
https://stackoverflow.com/questions/4111984
复制相似问题