Long Claw
Long Claw

Reputation: 107

C POSIX function lseek returns -1 but errno is not set

I have encountered a situation where after calling lseek, I would get -1 as a return value but errno would remain unset.

From what I understand by reading the documentation for lseek, -1 return value would indicate an error.

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

I have the following code:

res = lseek(stream->descriptor, offset, whence);
if (res < 0) {
    int j = errno;
    printf("%d %d\n", res, j);
}

which prints -1 0

I have copied the errno value before calling printf just as suggested in this question but it is still set to 0.

Also, I have observed that if I add one more line the error disappears and lseek returns the correct value.

lseek(stream->descriptor, 0, SEEK_CUR);  // keep the cursor as it is
res = lseek(stream->descriptor, offset, whence);
if (res < 0) {
    int j = errno;
    printf("%d %d\n", res, j);
}

Now, if I've understood lseek correctly the line I've added should not do anything, but I may be mistaken since it solves the error in a dirty way.

Upvotes: 1

Views: 218

Answers (0)

Related Questions