Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does lseek allow me to set a negative file position?

Tags:

c

linux

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?

like image 595
Todd Branchflower Avatar asked Nov 30 '22 20:11

Todd Branchflower


1 Answers

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>
    
like image 93
Olaf Dietsche Avatar answered Dec 03 '22 08:12

Olaf Dietsche