#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/