Bruce
Bruce

Reputation: 35275

UNIX lseek/read/write behavior

If I have a file of size 5 and I use lseek to seek to position 10 and then read 1 byte from this position using read, the return value of read system call is 0. I want to know the return value of lseek/read/write in the following case: If I seek past the maximum file size allowed by the file system and then perform read. Can we lseek to this position/Is it an error? If not if I do a read here what will be the return value of read? 0 or -1?

Upvotes: 1

Views: 4868

Answers (1)

paxdiablo
paxdiablo

Reputation: 881523

The POSIX specs for lseek() state that you are allowed to set the position beyond the end of the file:

The lseek() function shall allow the file offset to be set beyond the end of the existing data in the file.

It only complains if the resulting position is beyond the bounds of the off_t variable type returned from lseek(). There seem to be no error messages specified which indicate things like "beyond your process-specific limit" or "beyond the capacity of the filesystem itself".


However, trying to extend the file after that seek with a write() can return the EFBIG error code, again according to POSIX. Best bet would be to actually try this and see what the behaviour is, especially since Linux doesn't necessarily comply with POSIX in all cases - in other words, the behaviour may be different between POSIX-compliant UNIX systems and Linux.


The POSIX read() specs are quite adamant about what happens:

No data transfer shall occur past the current end-of-file. If the starting position is at or after the end-of-file, 0 shall be returned.

Hence, you should get back zero since, by definition, if you've done an lseek() beyond the capacity of the filesystem, you're assuredly beyond the end of the file (you can't create files bigger than the filesystem allows).

Upvotes: 5

Related Questions