说明:只供学习交流,装载请注明出处
对文件进行读写操作时,读取和写入文件的位置通过相对于文件起始内容的偏移值来控制。lseek函数用来改变该位置。该函数的具体信息若下表:
lseek函数
头文件 | <sys/types.h> <unistd.h> | ||
函数形式 | off_t lseek(int fildes, off_t offset, int whence); | ||
返回值 | 成功 | 失败 | 是否设置errno |
返回从文件开始位置最后的偏移量 | -1 | 是 |
说明:fildes为文件描述符。offset为偏移量,正数表示正向偏移,负数表示负向偏移。whence设定从文件的哪里开始偏移,可能取值为:
SEEK_SET:文件开头
SEEK_CUR:当前位置
SEEK_END:文件结尾
其中SEEK_SET,SEEK_CUR,SEEK_END依次为0,1,2.。
范例:
(1):欲将读写位置移到文件的开头时:
lseek(int fildes, 0, SEEK_SET);
(2):欲将读写位置移到文件尾时:
lseek(int fildes, 0, SEEK_END);
(3):想要取得目前文件位置时:
Lseek(int fildes, 0, SEEK_CUR);
错误信息:
EBADF:fildes不是打开的文件描述符。
EINVAL:whence没有取SEEK_SET、SEEK_CUR或SEEK_END 3个值中的一个,或文件偏移量为负数。
EOVERFLOW:偏移量超过off_t的范围。
ESPIPE:fildes为管道、socket套接字、或FIFO的文件描述符。
实例:
程序实现了对指定文件内容的搜索功能。其功能类似于Linux系统中的grep命令。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char *argv[])
{
//用于保存输入要查询字符串的长度
int len = 0;
//用于保存文件的文件描述符
int fd;
//文件偏移量
long offset = 0;
//用于存储读出文件的内容
char buffer[1024] = {'\0'};
//用于统计查找得到了几次相同字符
int flag = 0;
if ( argc != 3 )
{
printf("Usage: %s \"string\" filename\n", argv[0]);
return (1);
}
len = strlen(argv[1]);
if ((fd = open(argv[2], O_RDONLY)) == -1)
{
perror("Cannot open the desired file");
return (1);
}
//不断读取文件内容,然后与给定的字符串比较,如果相同则将flag计数加1
while (1)
{
if (lseek(fd, offset, SEEK_SET) == -1)
{
perror("Cannot move the file pointer");
return (1);
}
if (read(fd, buffer, len) < len)
{
break;
}
buffer[len] = '\0';
if (strcmp(buffer, argv[1]) == 0)
{
flag++;
}
offset++;
}
if ( flag > 0 )
{
printf("Find the string: %s in the file : %s %d times\n", argv[1],argv[2],flag);
}
close(fd);
return (0);
}
运行结果:(在test.dat文件中查找simple出现的次数)
[root@localhost test]# ./lseek "simple" test.dat
Find the string: simple in the file : test.dat 2 times
[root@localhost test]#