Saturday, April 6, 2013

Seeking in File

lseek() is used to set the filepos of a file.  Seeking past end of file is allowed.  Read will return EOF and write will cause data to be written at the position.  The range between the old EOF to the filepos is filled with zeros logically but not physically.  In other words, the actual file size is smaller than what it is recorded.  Performance is enhanced as the hole will not initiate any real I/O.  The file is called a sparse file.

In lieu of lseek, Linux also provides pread and pwrite system calls.  p stands for positional.  Semantically, p-call is similar to a lseek follow by read/write.  Differences are (1) they do not change the file pointer upon completion and (2) they avoid potential race condition with using lseek, as threads share the same fole pointer.

No comments: