Move a file pointer to the specified location.
long _lseek( int handle, long offset, int origin );
__int64 _lseeki64( int handle, __int64 offset, int origin );
Routine | Required Header | Compatibility |
_lseek | <io.h> | Win 95, Win NT |
_lseeki64 | <io.h> | Win 95, Win NT |
For additional compatibility information, see Compatibility in the Introduction.
Libraries
LIBC.LIB | Single thread static library, retail version |
LIBCMT.LIB | Multithread static library, retail version |
MSVCRT.LIB | Import library for MSVCRT.DLL, retail version |
Return Value
_lseek returns the offset, in bytes, of the new position from the beginning of the file. _lseeki64 returns the offset in a 64-bit integer. The function returns –1L to indicate an error and sets errno either to EBADF, meaning the file handle is invalid, or to EINVAL, meaning the value for origin is invalid or the 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.
Parameters
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:
SEEK_SET
Beginning of file
SEEK_CUR
Current position of file pointer
SEEK_END
End of file
You can use _lseek to reposition the pointer anywhere in a file or beyond the end of the file.
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 = 1207