Linux 文件(续)
lseek()
每一个已打开的文件都有一个读写位置,当打开文件时通常其读写位置是指向文件开头。
fildes 为已打开的文件标识符。
offset:偏移量,每一读写操作所需要移动的距离,单位是字节的数量,可正可负(向前移,向后移)。
返回值:当调用成功时则返回目前的读写位置,也就是距离文件开头多少个字节。若有错误则返回-1。
whence为下列其中一种:(SEEK_SET,SEEK_CUR和SEEK_END和依次为0,1和2)
SEEK_SET 将读写位置指向文件头后再增加offset个位移量。
SEEK_CUR 以目前的读写位置往后增加offset个位移量。
SEEK_END 将读写位置指向文件尾后再增加offset个位移量。
当whence 值为SEEK_CUR 或SEEK_END时,参数offset允许负值的出现。
例如:
读出已有文件的第2个字节内容。
如何获得当前偏移量?
如何计算文件的大小?
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#define BUFFER_SIZE 1024
main()
{
int fd , currpos;
char buf[BUFFER_SIZE];
fd = open("testfile01",O_RDWR);
printf("fd = %d\n",fd);
lseek(fd,1,SEEK_SET);
read(fd,buf,1);
printf("%c\n",buf[0]);
currpos = lseek(fd,0,SEEK_CUR);
printf("Current Position is : %d\n",currpos);
currpos = lseek(fd,0,SEEK_END);
printf("End Position is : %d\n",currpos);
close(fd);
}

浙公网安备 33010602011771号