Syntax
#include <io.h> /* constants in <stdio.h> */ long lseek(int handle, long offset, int origin);Description
lseek moves any file pointer associated with handle to a new location that is offset bytes from the origin. The next operation on the file takes place at the new location. The origin must be one of the following constants, defined in <stdio.h>: compact break=fit.
Origin
lseek can reposition the pointer anywhere in a file. The pointer can also be positioned beyond the end of the file; the data between the EOF and the new file position is undefined. (See chsize for more information on extending the length of the file.) An attempt to position the pointer before the beginning of the file causes an error.
Note: In earlier releases of C Set ++, lseek began with an underscore (_lseek). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, The Developer's Toolkit will map _lseek to lseek for you.
lseek returns the offset, in bytes, of the new position from the beginning of the file. A return value of -1L indicates an error, and lseek sets errno to one of the following values: compact break=fit.
Value
On devices incapable of seeking (such as keyboards and printers), lseek returns -1 and sets errno to EOS2ERR.
This example opens the file sample.dat and, if successful, moves the file pointer to the eighth position in the file. The example then attempts to read bytes from the file, starting at the new pointer position, and reads them into the buffer.
#include <io.h>#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> int main(void) { long length; int fh; char buffer[20]; memset(buffer, '\0', 20); /* Initialize the buffer */ printf("\nCreating sample.dat.\n"); system("echo Sample Program > sample.dat"); if (-1 == (fh = open("sample.dat", O_RDWR|O_APPEND))) { perror("Unable to open sample.dat."); exit(EXIT_FAILURE); } if (-1 == lseek(fh, 7, SEEK_SET)) { /* place the file pointer at the */ perror("Unable to lseek"); /* eighth position in the file */ close(fh); return EXIT_FAILURE; } if (8 != read(fh, buffer, 8)) { perror("Unable to read from sample.dat."); close(fh); return EXIT_FAILURE; } printf("Successfully read in the following:\n%s.\n", buffer); close(fh); return 0; /**************************************************************************** The output should be: Creating sample.dat. Successfully read in the following: Program . ****************************************************************************/ }Related Information