Search code examples
apimacosdarwin

Why does lseek return 0?


lseek() is supposed to return the position of the file descriptor.

The documentation says:

Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. Otherwise, a value of -1 is returned and errno is set to indicate the error.

Trouble is, not even this works:

#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);

This gives me:

size off_t: 8
pos: 0
pos: 0

Why is this? Is there an alternative to find the current offset, using the raw I/O functions? (read, open, lseek, …)

Edit 1:

I tried to make the example simpler.


Solution

  • Try adding #include <unistd.h> to the top.

    See: http://forums.macosxhints.com/archive/index.php/t-35508.html

    Basically, since you didn't #include <unistd.h>, the compiler is "guessing" that lseek() returns an int.

    Probably an int is 4-bytes long, and since PPC is "big-endian" byte order, you're getting the "top" 4 bytes, which are all zero.

    Include unistd.h lets the compiler realize that lseek() is returning an off_t, so you don't lose half the bytes.