C printf 编译器警告

标签 c printf

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

这给我错误如下:

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 *'

请帮我解决这个问题。

最佳答案

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

data 是一个 char *%c 格式说明符告诉 printf 需要一个 char。要从 char * 获取 char,您需要使用 * 运算符解引用指针。

也就是说,您的程序仍然无法正常工作,因为您没有在打印循环中递增 counter,也没有对其进行初始化。我会选择:

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

相反。我没有检查您程序的其余部分,但鉴于我查看的三行中存在三个严重错误,我怀疑其余部分是否没有错误。

关于C printf 编译器警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4112070/

相关文章:

c - 预测由 C (glibc) rand() 生成的下一个数字

c - Linux的systemd的udev使用的 "keyboard-keys-from-name.h"在哪里?

c - 带有关系符号的 printf

c++ - 在 `h` 中使用标签 `hh` 或 `printf` 是否涉及未定义的行为?

OCaml Printf.sprintf

c - 如何解决此打印输出问题?

c - 为什么 struct int 值没有被传递到下一个函数?

c - 如何在文件系统中实现类似碎片整理的方法

不能一个接一个地建立一个tcp连接

c - 如何确定真正需要的char数组的大小?