Changing the file offset
The lseek:whence: message is used to query and set the file offset. This is the position in the file used by read:startingAt:nbyte: and write:startingAt:nbyte: when transferring data. A successful read or write operation automatically sets the file offset to point after the last byte read or written.
The lseek:whence: message is sent to an open CfsFileDescriptor instance. The first argument, offset, is an integer offset into the file. The second argument, whence, is one of the constants shown in the following table, which are defined in the CfsConstants pool dictionary. The lseek:whence: message answers an integer representing the new file offset.
Table 11. Whence constants for the lseek:whence: message
Pool variable
Description
SEEKSET
The file offset is set to the position specified by the first argument. An offset of 0 sets the file offset to the beginning of the file.
SEEKCUR
The file offset is set to its current position plus the number of bytes specified by the first argument.
SEEKEND
The file offset is set to the file size plus the number of bytes specified by the first argument.
Some examples of the use of lseek:whence: follow:
| fd current |
"Open an existing file for reading, fail if it does not exist"
(fd := CfsFileDescriptor
open: 'exists.txt'
oflag: ORDONLY) isCfsError
ifTrue: [^self error: fd message].
"Get the current file pointer position"
current := fd lseek: 0 whence: SEEKCUR.
Transcript cr; show: 'Current position: ', current printString.
"Seek to 5 bytes before the end of the file"
fd lseek: -5 whence: SEEKEND.
"Seek to the beginning of the file"
fd lseek: 0 whence: SEEKSET.
"Seek after 10th byte of file, next read or write
will start with 11th byte"
fd lseek: 10 whence: SEEKSET.
"Rewind file pointer by 20 bytes"
fd lseek: -20 whence: SEEKCUR.
fd close.
Last modified date: 05/12/2020