LSEEK(DOS) UNIX System V LSEEK(DOS)
Name
lseek - Changes the position of a file pointer.
Syntax
#include <io.h>
#include <stdio.h>
long lseek(handle, offset, origin)
int handle;
long offset;
int origin;
Description
The lseek function moves the file pointer associated with
handle to a new location that is offset bytes from origin.
The next operation on the file occurs at the new location.
The origin must be one of the following constants defined in
stdio.h:
Origin Definition
SEEK_SET Beginning of file
SEEK_CUR Current position of file pointer
SEEK_END End of file
The lseek function can be used to reposition the pointer
anywhere in a file. The pointer can also be positioned
beyond the end of the file. However, an attempt to position
the pointer before the beginning of the file causes an
error.
Page 1 (printed 7/6/89)
LSEEK(DOS) UNIX System V LSEEK(DOS)
Return Value
The lseek function returns the offset, in bytes, of the new
position from the beginning of the file. A return value of
-1L indicates an error, and errno is set to one of the
following values:
Value Meaning
EBADF Invalid file handle
EINVAL Invalid value for origin, or position
specified by offset is before the
beginning of the file
On devices incapable of seeking (such as terminals and
printers), the return value is undefined.
See Also
fseek(DOS), tell(DOS)
Example
#include <io.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
int fh;
long pos; /* position of file pointer */
char buffer[10];
main()
{
fh = open("data",O_RDONLY);
/* Seek the beginning of the file: */
pos = lseek(fh,0L,SEEK_SET);
if (pos == -1L)
perror("lseek to beginning failed");
else
printf("Position for beginning of file seek = %d\n", pos);
read(fh,buffer,10); /* Move file pointer a little */
Page 2 (printed 7/6/89)
LSEEK(DOS) UNIX System V LSEEK(DOS)
/* Find current position: */
pos = lseek(fh,0L,SEEK_CUR);
if (pos == -1L)
perror("lseek to current position failed");
else
printf("Position for current position seek = %d\n", pos);
/* Set the end of the file: */
pos = lseek(fh,0L,SEEK_END);
if (pos == -1L)
perror("lseek to end failed");
else
printf("Position for end of file seek = %d\n", pos);
}
This program first opens a file named data. It then uses
lseek to find the beginning of the file, to find the current
position in the file, and to find the end of the file.
Page 3 (printed 7/6/89)