博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Linux-lseek

Posted on 2023-03-14 07:03  乔55  阅读(57)  评论(0编辑  收藏  举报

当前文件偏移量

  • 所有打开的文件都有一个当前文件偏移量,current file offset,以下简称为cfo
  • 当前文件偏移量,即是当前文件指针位置
  • cfo通常是一个非负整数,用于表明文件开始处到当前文件指针位置的字节数
  • 读写操作通常开始于cfo,并且能使cfo增大,增量即为读定的字节数
  • 文件打开时,cfo会被初始化为0,除非使用了O_APPEND

lseek详解

off_t lseek(int fd, off_t offset, int whence);

// 功能:移动文件指针。若执行成功,则返回新的当前文件偏移量


描述:The  lseek() function repositions the offset of the open file associated with the file descriptor fd 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.
// 把文件指针位置设置为:whence+offset
// SEEK_SET:当前文件指针在:offset处
// SEEK_CUR:当前文件指针在:cfo+offset处
// SEEK_END:当前文件指针在:文件长度+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 ('\0') until data is actually written into the gap.
// lseek()允许把文件偏移量设置为超出文件末尾的位置,且并不会改变文件大小
// 如果数据后来被写入到这个偏移量位置,在把数据真正写入这段空洞位置之前
// 读取这段空间返回的都是'\0',

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.
// 成功,则返回文件当前指针距离文件开头的偏移量,失败则返回-1并设置errno

lseek例子


lseek(fd, 0, SEEK_SET);  
// 当前文件指针在开头位置

int pos = lseek(fd, 0, SEEK_CUR);
// 获取当前文件指针位置

int file_size = lseek(fd, 0, SEEK_END);
// 获取文件长度

off_t curPos = lseek(fd, 1000, SEEK_END);
// 从文件尾部向后扩展1000个字节
// 但需要额外执行一次读写操作,否则无法完成扩展

int truncate(const char *path, off_t length);
int ret = truncate("b.txt", 1024);
// 将b.txt长度截断了1024个字节。要求b.txt必须存在。


lseek的主要作用

  • 获取文件大小
  • 移动文件指针
  • 文件拓展