lseek()函数的头文件和形式:
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int filedes, off_t offset, int whence) ;
lseek()函数的说明:
打开的每个文件都有一个与其相关联的“当前文件位移量”。它是一个非负的整数,用以度量从文件开始处计算的字节数。
通常,读、写操作都从当前文件位移量处开始,并使位移量增加所读或写的字节数。按系统默认,当打开一个文件时,
除非指定O_A P P E N D选择项,否则该位移量被设置为0。
lessk()函数的参数说明:
第一个参数是文件描述符;第二个参数是偏移量,int型的数,正数是向后偏移,负数向前偏移;第三个参数是有三个选项:
1.SEEK_SET:将文件指针偏移到传入字节数处(文件头开始偏移)
2.SEEK_CUR:将文件指针偏移到当前位置加上传入字节数处;((当前位置开始偏移)
3.SEEK_END:将文件指针偏移到文件末尾加上传入字节数处(作为拓展作用,必须再执行一次写操作)
实例代码
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
/*用lseek函数拓展文件*/
/*int main(){
int fd, ret;
//打开文件夹
fd = open("example.text", O_RDWR);
if(fd == -1){
perror("open");
exit(1);
}
//查看文件当前的大小
ret = lseek(fd, 0, SEEK_END);
printf("file value = %d\n", ret);
//文件拓展1000字节
ret = lseek(fd, 1000, SEEK_END);
printf("return value = %d\n", ret);
//实现文件拓展,必须再执行一次写操作
write(fd, "hello", 6);
close(fd);
return 0;
}*/
//将已存在的文件按相反顺序拷贝到另一个文件中
int main(){
int fd1, fd2;
char ch;
//打开已存在文件和新建文件
fd1 = open("a.txt", O_RDONLY);
fd2 = open("b.txt", O_WRONLY | O_CREAT | O_TRUNC, 0777);
lseek(fd1, -1, SEEK_END);//将文件位移量偏移到最后一个字符前
read(fd1, &ch, 1);
write(fd2, &ch, 1);
//循环读取和写入
while(lseek(fd1, -2, SEEK_CUR) != -1){
read(fd1, &ch, 1);
write(fd2, &ch, 1);
}
close(fd1);
close(fd2);
}