所有打开的文件都有一个当前文件偏移量,也叫读写偏移量和指针。文件偏移量通常是一个非负整数,用于表明文件开始处到文件当前位置的字节数(下一个read或?write操作的文件起始位置)。文件的第一个字节的偏移量为0。
文件打开时,会将文件偏移量设置为指向文件开始(使用特别的flags 除外,例如O_APPEND),之后每次read和write会自动对其调整,以指向已读或已写数据的下一字节。因此连续的read和write将按顺序递进,对文件进行操作。
1.lseek
用于重新定位文件内的读/写文件偏移量。
2.头文件
#include <sys/types.h>
#include <unistd.h>
3.函数原型
off_t lseek(int fd, off_t offset, int whence);
4.参数
1)fd:表示要操作文件的文件描述符。
2)offset:表示以whence为起始点的偏移字节数。
3)whence:表示offset的起始点位置,可以是以下之一:
SEEK_SET:文件的开头。
SEEK_CUR:当前读写位置。
SEEK_END:文件的末尾。
5.返回值
若成功执行,则返回新的偏移量(单位是字节);若失败,返回-1。
6.示例:(打开test文件,将位置指针移动到文件末尾,查看内容长度)
| #include <sys/types.h>
#include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> int main() { int fd = open("./test", O_RDWR); if (fd < 0) { printf("error: test openn"); return -1; } int lk = lseek (fd, 0, SEEK_END); if (lk < 0) { printf("error: test lseekn"); close(fd); return -1; } printf("lseek fd: %dn", lk); close(fd); return 0; } |
7.编译运行并查看测试结果
| lseek fd: 15 ???????????????//"HELLO WORLD!!!n"是15字节 |
551