format error in printf [duplicate]
Possible Duplicate:
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 || o开发者_StackOverflow社区ffset > 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;
}
when i run this code it give me error as
gcc mmap.c -o mmap mmap.c: In function 'main': mmap.c:38: warning: format '%d' expects type 'int', but argument 3 has type 'long int'
please tell me, why it is happening?
I believe you are missing code.
But, in one of your printf statements your are using the %d flag but intstead need to use the %ld.
Edit:
Heres the bug:
fprintf(stderr, "mmapdemo: offset must be in the range 0 - %d \n",
sbuf.st_size-1);
should be:
fprintf(stderr, "mmapdemo: offset must be in the range 0 - %ld \n",
sbuf.st_size-1);
Your code doesn't show up properly. The error that you are getting is just a warning. It means that you are using the wrong format string. For long int you probably should use %ld .
Use %ld
Hmm, the snippet you posted doesn't look like it has 38 lines in it, but the error you cite comes from using the format %d
instead of %ld
or one of its related C99 symbolic formats.
Ok, now there is more code posted. While st_size
is technically off_t
, and there is no C99 format specifier for off_t, %zd
will print a size_t
and conforms to C99. It's probably your best best.
However, as a practical matter, %ld
will also work and is an acceptable choice.
Update: Ok, I was giving you advice on making your program compile, but R is pointing out that a portable program should run on at least ILP32, LP64, and LLP64, so it will be necessary in that case to cast to whatever type you have in the format, and that if you want all 64-bits to actually print on all those systems, about the only choice is %lld
and a cast to (long long)
.
This:
fprintf(stderr, "mmapdemo: offset must be in the range 0 - %d \n",sbuf.st_size-1);
should be:
fprintf(stderr, "mmapdemo: offset must be in the range 0 - %ld \n",sbuf.st_size-1);
精彩评论