需要包含两个头文件
#include <sys/types.h>
#include <unistd.h>
函数名
off_t lseek(int fd, off_t offset, int whence);
fd:文件描述符
offset:对于whence的偏移值,负数表示左,正数表示右,0表示原地
whence:固定点的位置
whence有三个固定宏:
SEEK_SET:文件头
SEEK_CUR:文件当前位置
SEEK_END:文件尾巴
应用
lseek(fd_file1,0,SEEK_SET);//光标移到文件头部
lseek(fd_file1,0,SEEK_CUR);//光标保留当前位置
lseek(fd_file1,0,SEEK_END);//光标移到文件尾部
lseek(fd_file1,5,SEEK_SET);//光标移到相对于文件头部右边5个byte
lseek(fd_file1,5,SEEK_CUR);//光标相对于当前位置右边5个byte
lseek(fd_file1,-5,SEEK_END);//光标相对于当前位置文件尾部左边5个byte
返回值
成功
Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file.
成功完成后,lseek()返回相应的偏移量从文件开始的字节数。
利用这个特性可以计算文件的大小
int file1_size =lseek(fd_file1,0,SEEK_END);
printf("write file1 size = %d\n",file1_size);
失败
On error,the value (off_t) -1 is returned and errno is set to indicate the error.
发生错误时,返回值(off_t) -1,并设置errno来指示错误。
应用场景
当连续进行文件写入与文件读出时,需注意光标位置,当写入发生后,光标不会自动跳转到文件头,需重启文件或执行移动光标函数。