Search code examples
clinuxlseek

What if lseek() pass beyond the beginning of the file?


As the documentation highlighted, the lseek() function allows the file offset to be set beyond the end of the file. But what if I set it beyond the beginning of the file?

Let the current offset be 5, What will actually happen when I try lseek(fd, 10, SEEK_END) ?

As mentioned, assume that I create a new file, and call the function write(fd, buf, 5) . The current file offset would be 5. Then using lseek function above, I expect the result would either be 0 or some errors may occurred.


Solution

  • Assuming that what you're asking if you can seek to before the beginning of the file (which your code example wouldn't do):

    The specification for lseek() says that it will return -1 and set errno to EINVAL:

    The whence argument is not a proper value, or the resulting file offset would be negative for a regular file, block special file, or directory.