Arquivo head:
#include <sys / types.h>
#include <unistd.h>
Protótipo de função:
off_t lseek(int fd, off_t offset, int whence);
fd : Indica o descritor de arquivo a ser operado
deslocamento : é o deslocamento baseado em whoce (-5 é 5 bytes para a esquerda, 3 é 3 bytes para a direita)
de onde : SEEK_SET (o cursor está no início do arquivo);
SEEK_CUR (o cursor está na posição atual);
SEEK_END (o cursor está no final do conteúdo do arquivo);
Valor de retorno : Sucesso: o tamanho em bytes do cursor até o início do arquivo; erro: retorno -1 (você pode usar o valor de retorno para calcular o número de bytes)
Código:
#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf = "123456789abcdefg";
fd = open("./file-lseek",O_RDWR|O_CREAT,0600);
int n_write = write(fd,buf,strlen(buf));
char *readBuf;
readBuf = (char *)malloc(sizeof(char)*n_write);
lseek(fd,0,SEEK_SET);// 光标位于文件的开头
int n_read = read(fd,readBuf,n_write);// 读取之后,此时光标位于文件的末尾
printf("readBuf-1: %s\n",readBuf);
memset(readBuf,'\0',n_write);// 初始化 readBuf 指向的空间
lseek(fd,-7,SEEK_CUR);// 将此时的光标位置向左移动 7 个字节
read(fd,readBuf,n_write);
printf("readBuf-2: %s\n",readBuf);
memset(readBuf,'\0',n_write);
lseek(fd,0,SEEK_SET);// 将光标移动到文件开头
int size = lseek(fd,0,SEEK_END); //光标移动到文件末尾,返回值是光标从文件开头移动到末尾的字节数
printf("size = %d\n",size);
}