_lseek

Description

Moves a file pointer to the specified location.

#include <io.h> Required only for function declarations  
#include <stdio.h>    

long _lseek( int handle, long offset, int origin );

handle Handle referring to open file  
offset Number of bytes from origin  
origin Initial position  

Remarks

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 argument must be one of the following constants, which are 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.

Return Value

The _lseek function returns the offset, in bytes, of the new position from the beginning of the file. The function returns –1L to indicate an error and sets errno 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.

Compatibility

Standards:UNIX

16-Bit:DOS, QWIN, WIN, WIN DLL

32-Bit:DOS32X

Use _lseek for compatibility with ANSI naming conventions of non-ANSI functions. Use lseek and link with OLDNAMES.LIB for UNIX compatibility.

See Also

fseek, _tell

Example

/* LSEEK.C: This program first opens a file named LSEEK.C.

* 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.

*/

#include <io.h>

#include <fcntl.h>

#include <stdlib.h>

#include <stdio.h>

void main( void )

{

int fh;

long pos; /* Position of file pointer */

char buffer[10];

fh = _open( "lseek.c", _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 = %ld\n", pos );

/* Move file pointer a little */

_read( fh, buffer, 10 );

/* 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 = %ld\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 = %ld\n", pos );

_close( fh );

}

Output

Position for beginning of file seek = 0

Position for current position seek = 10

Position for end of file seek = 1183