The man entry says lseek
should return -1
if the resulting file offset would be negative for a regular file.
Why does code like this work?
int fd;
off_t offset;
fd = open("test.txt", O_RDWR);
offset = lseek(fd, -10, SEEK_SET);
printf("%d\n", offset); // prints -10
if (offset == (off_t) -1)
perror("seek"); // error not triggered
I feel like I should get offset=-1
and errno
set to EINVAL
.
This also causes the file size to appear extremely large (close to the size of an unsigned int) - seems like an overflow issue. Why is that?
I managed to reproduce your "erroneous" behaviour. You must include unistd.h
to get the proper prototype. With this include, lseek
behaves as described.
When you miss this include, the compiler passes an int -10
instead of an off_t -10
. This results in your observed behaviour.
Update:
The complete list of needed includes is
open(2)
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
lseek(2)
#include <sys/types.h>
#include <unistd.h>
printf(3)
,
perror(3)
#include <stdio.h>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With