需调用函数:
off_t lseek(int fd, off_t offset, int whence);
需调用头文件:
#include <sys/types.h>
#include <unistd.h>
在此函数第三个参数中SEEK_SET,将光标返回文件头
SEEK_END将光标指向文件尾,SEEK_CUR将光标指向当前位置。
第二个参数,即移动的字节,经代码调制后可知,第二个参数正常情况下向后移动字节,若想向前移动字节,需要加上负号。
代码展示:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf = "qybs hen shuai!";
fd = open("./file1",O_RDWR);
if(fd == -1){
printf("open failed\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf("creat succeed\n");
}
}
printf("creat succeed! fd = %d\n",fd);
int n_write = write(fd, buf,strlen(buf));
if(n_write != -1){
printf("write %d byte to file\n",n_write);
}
char *readBuf;
readBuf = (char *)malloc(sizeof(char)*n_write + 1);
lseek(fd, -15,SEEK_CUR);
int n_read = read(fd,readBuf,n_write);
printf("read:%d,context:%s\n",n_read,readBuf);
close(fd);
return 0;
}