gtpc2m4nC/C++ Language Support User's Guide

lseek-Change the Offset of a File

This function sets the file offset.

Format

#include <unistd.h>
off_t lseek(int fildes,off_t offset,int pos);

fildes
The file descriptor whose file offset you want to set.

off_t offset
The amount (positive or negative) that the byte offset will be changed. The sign (+ or -) indicates whether the offset is to be moved forward (positive) or backward (negative).

pos
The position in the file to start the change.

Specify one of the following symbols (defined in the unistd.h header file):

SEEK_SET
The start of the file.

SEEK_CUR
The current file offset in the file.

SEEK_END
The end of the file.

The new position is the byte offset from the position specified by pos. After you have used the lseek function to seek to a new location, the next I/O operation on the file begins at that location.

The lseek function lets you specify new file offsets beyond the current end of the file. If data is written at such a point, read operations in the gap between this data and the old end of the file will return bytes containing zeros. (In other words, the gap is assumed to be filled with zeros.)

Seeking past the end of a file, however, does not automatically extend the length of the file. There must be a write operation before the file is actually extended.

Normal Return

If successful, the lseek function returns the new file offset, measured in bytes, from the beginning of the file.

Error Return

If unsuccessful, the lseek function returns a value of -1 and sets errno to one of the following:

EBADF
fildes is not a valid open file descriptor.

EINVAL
pos contained something other than one of the three options, or the combination of the pos and off_t offset values would have placed the file offset before the beginning of the file, or the size of the file cannot be determined.

Programming Considerations

Examples

The following example positions a file (that has at least 10 bytes) to an offset of 10 bytes before the end of the file.

lseek(fildes,-10,SEEK_END);

Related Information

See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.