server-api-lseek

原型

对当前打开的文件的操作位置进行移动。
每次打开和对文件进行读写操作后,文件的偏移量都进行了更新。当写入数据成功时,文件的偏移量要向后移动写入数据的大小。当从文件中读取数据的时候,文件的偏移量要向后移动读出数据的大小。
文件的偏移量是一个非负整数,表示从文件的开始到当前位置的字节数。一般情况下,对文件的读取操作都从当前的文件位移量处开始,并增加读写操作成功的字节数。当打开一个文件时,如果没有指定O_APPEND选项,文件的位移量为0。如果指定了O_APPEND选项,文件的偏移量与文件的长度相等,即文件的当前操作位置移到了末尾。

由于使用文件偏移量可以为负值,判断lseek是否操作成功时,不要使用小于0的判断,要使用是否等于-1来判断函数失败。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <sys/types.h>
#include <unistd.h>

// 功能说明:通过指定相对于开始位置、当前位置或末尾位置的字节数来重定位curp,这取决于lseek()函数中指定的位置
// 与C的fseek相同
// fd:需要设置的文件标识符
// offset:偏移量
// whence:搜索的起始位置(unistd.h)
// SEEK_SET:从文件开始处计算偏移
// SEEK_CUR:从当前文件的偏移值计算偏移
// SEEK_END:从文件的结束处计算偏移
// 返回值:
// 如果操作成功,返回新的文件的偏移量的值
// 如果操作失败,返回-1
off_t lseek(int fd, off_t offset, int whence);

使用参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

#define ERR_EXIT(m)\
do \
{\
perror(m);\
exit(EXIT_FAILURE);\
}while(0)

int main()
{
int fd;
fd = open("test.txt", O_RDONLY);
if(fd == -1)
ERR_EXIT("open error");

char buf[1024] = {0};
int ret = read(fd, buf, 5);
if(ret == -1)
ERR_EXIT("read error");
printf("buf=%s\n", buf);

ret = lseek(fd, 0, SEEK_CUR);
if(ret == -1)
ERR_EXIT("lseek");

printf("current offset=%d\n", ret);
return 0;
}