From: http://linux.die.net/man/2/lseek
Name
lseek - reposition read/write file offset
Synopsis
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, intwhence);
Description
The lseek() function repositions the offset of the open file associated with the file descriptorfd to the argument offset according to the directive whence as follows:
-
SEEK_SET
- The offset is set to offset bytes. ( 当前位置为文件的开头,新位置为偏移量大小) SEEK_CUR
- The offset is set to its current location plus offset bytes. ( 当前位置为文件指针位置,新位置为当前位置加上偏移量大小) SEEK_END
- The offset is set to the size of the file plus offset bytes.( 当前位置为文件结尾,新位置为文件结尾往后偏移量offset处)
The lseek() function allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a "hole") return null bytes (aq\0aq) until data is actually written into the gap.
Seeking file data and holes
Since version 3.1, Linux supports the following additional values for whence:
-
SEEK_DATA
- Adjust the file offset to the next location in the file greater than or equal to offset containing data. If offset points to data, then the file offset is set to offset. 调整文件偏移为大约等于offset且包含数据处. 如果offset指向数据处,则文件的偏移设置为offset SEEK_HOLE
- Adjust the file offset to the next hole in the file greater than or equal to offset. If offset points into the middle of a hole, then the file offset is set to offset. If there is no hole past offset, then the file offset is adjusted to the end of the file (i.e., there is an implicit hole at the end of any file). 调整文件的偏移为大于等于offset的下一处hole处。如果offset指向一个hole的中间,则文件偏移设置为offset.如果经过offset文件中没有hole,则文件的偏移调整为文件结尾(即在任何文件结尾都隐含有一个hole).
In both of the above cases, lseek() fails if offset points past the end of the file 在上面2种case种,如果offset超过文件结尾,lseek()返回错误
Return Value
Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value(off_t) -1 is returned and errno is set to indicate the error.
Errors
-
EBADF
- fd is not an open file descriptor. EINVAL
- whence is not valid. Or: the resulting file offset would be negative, or beyond the end of a seekable device. EOVERFLOW
- The resulting file offset cannot be represented in an off_t. ESPIPE
- fd is associated with a pipe, socket, or FIFO. ENXIO
- whence is SEEK_DATA or SEEK_HOLE, and the current file offset is beyond the end of the file.
Notes
1. When converting old code, substitute values forwhence with the following macros:
old | new |
0 | SEEK_SET |
1 | SEEK_CUR |
2 | SEEK_END |
L_SET | SEEK_SET |
L_INCR | SEEK_CUR |
L_XTND | SEEK_END |
2. About type off_t --->long
include/linux/Types.h
typedef __kernel_off_t off_t;
include/asm-generic/Posix_types.h
typedef __kernel_long_t __kernel_off_t;
typedef long __kernel_long_t;