为什么lseek会返回0?

Geo*_*lly 2 api macos darwin

lseek() 应该返回文件描述符的位置.

文件说:

成功完成后,lseek()将返回从文件开头以字节为单位的结果偏移位置.否则,返回值-1,并设置errno以指示错误.

麻烦的是,这甚至不起作用:

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
printf("size off_t: %i\n", sizeof(off_t));

off_t pos;
pos = lseek(file, (off_t)0, SEEK_CUR);
printf("pos: %lli\n", pos);

// same result for SEEK_SET and SEEK_END
pos = lseek(file, (off_t)2352, SEEK_CUR);
printf("pos: %lli\n", pos);
Run Code Online (Sandbox Code Playgroud)

这给了我:

size off_t: 8
pos: 0
pos: 0

为什么是这样?是否有使用原始I/O功能查找当前偏移的替代方法?(read,open,lseek,...)

编辑1:

我试图让这个例子更简单.

小智 6

尝试将#include <unistd.h>添加到顶部.

请参阅:http://forums.macosxhints.com/archive/index.php/t-35508.html

基本上,既然你没有#include <unistd.h>,编译器会"猜测" lseek()返回一个int.

可能一个int是4字节长,并且因为PPC是"大端"字节顺序,所以你得到的是"顶部"4个字节,它们都是零.

包含unistd.h让编译器实现lseek()返回off_t,所以你不会丢失一半的字节.