ptg10805159
Section 3.6 lseekFunction 67
An open file’s offset can be set explicitly by callinglseek.
#include <unistd.h>
off_t lseek(intfd,off_toffset,int whence);
Returns: new file offset if OK,−1 on error
The interpretation of theoffsetdepends on the value of thewhenceargument.
•IfwhenceisSEEK_SET,the file’s offset is set tooffsetbytes from the beginning of
the file.
•IfwhenceisSEEK_CUR,the file’s offset is set to its current value plus theoffset.
Theoffsetcan be positive or negative.
•IfwhenceisSEEK_END,the file’s offset is set to the size of the file plus theoffset.
Theoffsetcan be positive or negative.
Because a successful call tolseekreturns the new file offset, we can seek zerobytes
from the current position to determine the current offset:
off_t currpos;
currpos = lseek(fd, 0, SEEK_CUR);
This technique can also be used to determine if a file is capable of seeking. If the file
descriptor refers to a pipe,FIFO, or socket,lseeksetserrnotoESPIPEand returns−1.
The three symbolic constants —SEEK_SET,SEEK_CUR,andSEEK_END—wereintroduced
with System V.Prior to this,whencewas specified as 0 (absolute), 1 (relative to the current
offset), or 2 (relative to the end of file). Much softwarestill exists with these numbers hard
coded.
The characterlin the namelseekmeans ‘‘long integer.’’Beforethe introduction of the
off_tdata type, theoffsetargument and the return value werelong integers.lseekwas
introduced with Version 7 when long integers wereadded to C. (Similar functionality was
provided in Version 6 by the functionsseekandtell.)
Example
The program in Figure3.1 tests its standardinput to see whether it is capable of seeking.
#include "apue.h"
int
main(void)
{
if (lseek(STDIN_FILENO, 0, SEEK_CUR) == -1)
printf("cannot seek\n");
else
printf("seek OK\n");
exit(0);
}
Figure 3.1 Te st whether standardinput is capable of seeking