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 *'
请帮我解决问题。
#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;
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
data
是一个char *
。%c
格式说明符告诉printf
需要一个char
。要从char *
获取char
,您需要使用*
运算符取消引用指针。也就是说,您的程序仍然无法正常工作,因为您没有在打印循环中递增计数器,也没有初始化它。我会选择:
相反。我没有检查你的程序的其余部分,但鉴于我查看的三行中有三个严重错误,我怀疑其余部分没有错误。
data
is achar *
. The%c
format specifier tellsprintf
to expect achar
. To get achar
from achar *
, 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: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.
要逐字节打印出来,需要使用
or 打印出十六进制值:
to print it out byte by byte, need to use
or to print out the hex values: