Set the current file position at the operating-system level
#include <sys/types.h> #include <unistd.h> off_t lseek( int filedes, off_t offset, int whence ); off64_t lseek64( int filedes, off64_t offset, int whence );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
These functions set the current file position for the file descriptor specified by filedes at the operating system level. File descriptors are returned by a successful execution of one of the creat(), dup(), dup2(), fcntl(), open() or sopen() functions.
An error occurs if the requested file position is before the start of the file.
If the requested file position is beyond the end of the file and data is written at this point, subsequent reads of data in the gap will return bytes whose value is equal to zero ('\0') until data is actually written into the gap.
These functions don't extend the size of a file (see chsize()).
The current file position, with 0 indicating the start of the file, or -1 if an error occurs (errno is set).
Using the lseek() function, you can get the current file position (in fact, tell() is implemented this way). You can then use this value with another call to lseek() to reset the file position:
off_t file_posn; int filedes; /* get current file position */ file_posn = lseek( filedes, 0L, SEEK_CUR ); … /* return to previous file position */ file_posn = lseek( filedes, file_posn, SEEK_SET );
If all records in the file are the same size, the position of the nth record can be calculated and read like this:
#include <sys/types.h> #include <unistd.h> int read_record( int filedes, long rec_numb, int rec_size, char *buffer ) { if( lseek( filedes , rec_numb * rec_size, SEEK_SET ) == -1L ) { return -1; } return( read( filedes , buffer, rec_size ) ); }
The read_record() function in this example assumes records are numbered starting with zero, and that rec_size contains the size of a record in the file, including any record-separator characters.
lseek() is POSIX 1003.1; lseek64() is Large-file support
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |
chsize(), close(), creat(), dup(), dup2(), eof(), errno, execl(), execle(), execlp(), execlpe(), execv(), execve(), execvp(), execvpe(), fcntl(), fileno(), fstat(), isatty(), open(), read(), sopen(), stat(), tell(), umask(), write()