lseek的问题,请大侠帮忙,万分感激
代码测试如下:#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifndef O_DIRECT
#define O_DIRECT 040000
#endif
int main()
{
int fd = 0;
off_t off = 2495610880;
off_t real_off = 0;
printf("sizeof off_t = %d\n", sizeof(off_t));
if ((fd = open("/dev/raw/raw2", O_RDONLY|O_DIRECT)) < 0)
{
printf("open error\n");
return -1;
}
printf("open ok:%lx\n", off);
if ((real_off = lseek(fd, off, SEEK_SET)) != off)
{
printf("seek error:%lx\n", real_off);
printf("%d\n", errno);
perror("test2");
return -1;
}
printf("seek ok\n");
return 0;
}
执行结果:
sizeof off_t = 8
open ok:94c00000
seek error:ffffffff94c00000
0
test2: Success
请问为什么real_off会被扩充为ffffffff94c00000而导致seek error打印,万分苦恼,请大侠帮忙 gcc -Wall你就会知道原因了。
增加
#include <unistd.h>
即可 大神!我当初找了好久才发现了回复 2# hellioncu
回复 3# xiaoruoax
话说是为什么啊?楼主分享一下 隐式声明的lseek返回32位有符号整形,而off_t是64位无符号整形。
32转64时会做符号位拓展,0x94c00000的符号位是1,所以real_off的高32位都填成了1。
添加#incluide <unistd.h>
会使lseek返回64位无符号整形,不会出现符号位扩展,所以能解决问题。
页:
[1]