开发者

C printf compiler warning

#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);
    }

    if开发者_如何学C (stat("mmapdemo.c", &sbuf) == -1) {
     perror("stat");
        exit(1);
    }

    offset = atoi(argv[1]);
    if (offset < 0 || offset > sbuf.st_size-1) {
        fprintf(stderr, "mmapdemo: offset must be in the range 0-%ld\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;
}

This gives me error as follows:

gcc mmapdemo.c -o mmapdemo
mmapdemo.c: In function 'main':
mmapdemo.c:48: warning: format '%c' expects type 'int', but argument 2 has type 'char *'

Please help me to solve the problem.


printf("%c", *data++);

data is a char *. The %c format specifier tells printf to expect a char. To get a char from a char *, you need to dereference the pointer using the * operator.

That said, your program still won't work properly because you're not incrementing counter in your print loop, nor have you initialized it. I would go with:

for (size_t i = 0; i < sbuf.st_size; ++i) {
    printf("%c", data[i]);
}

instead. I haven't inspected the rest of your program, but given that there were three serious errors in three lines that I looked at, I doubt that the rest is bug-free.


to print it out byte by byte, need to use

printf("%c ", *data++)

or to print out the hex values:

printf("%02X", *data++);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜