lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms.
Required Include Files
#include <unistd.h> #include <sys/types.h>
Function Definition
off_t lseek(int fildes, off_t offset, int whence);
Field | Description |
---|---|
int fildes | The file descriptor of the pointer that is going to be moved. |
off_t offset | The offset of the pointer (measured in bytes). |
int whence | The method in which the offset is to be interpreted (relative, absolute, etc.). Legal values for this variable are provided at the end. |
return value | Returns the offset of the pointer (in bytes) from the beginning of the file. If the return value is -1, then there was an error moving the pointer. |
Code Snippet
The following is an example using the lseek system call.
#include <unistd.h> #include <fcntl.h> #include <sys/types.h> int main() { int file=0; if((file=open("testfile.txt",O_RDONLY)) < -1) return 1; char buffer[19]; if(read(file,buffer,19) != 19) return 1; printf("%s\n",buffer); if(lseek(file,10,SEEK_SET) < 0) return 1; if(read(file,buffer,19) != 19) return 1; printf("%s\n",buffer); return 0; }
The output of the preceding code is:
$ cat testfile.txt
This is a test file that will be used
to demonstrate the use of lseek.
$ ./testing
This is a test file
test file that will
Available Values for whence
Value | Meaning |
---|---|
SEEK_SET | Offset is to be measured in absolute terms. |
SEEK_CUR | Offset is to be measured relative to the current location of the pointer. |
SEEK_END | Offset is to be measured relative to the end of the file. |
c要学习的课程
ReplyDelete基本双链表碎片示例