一.需要導入的頭文件:
#include <sys/types.h>
#include <unistd.h>
定義函數原型:off_t lseek(int fildes, off_t offset, int whence);
二.函數說明:
每一個已打開的文件都有一個讀寫位置, 當打開文件時通常其讀寫位置是指向文件開頭, 若是以附加的方式打開文件(如O_APPEND), 則讀寫位置會指向文件尾.
當read()或write()時, 讀寫位置會隨之增加,lseek()便是用來控制該文件的讀寫位置. 參數fildes 為已打開的文件描述詞, 參數offset 為根據參數whence來移動讀寫位置的位移數.
參數 whence 為下列其中一種:
SEEK_SET 參數offset 即為新的讀寫位置.
SEEK_CUR 以目前的讀寫位置往后增加offset 個位移量.
SEEK_END 將讀寫位置指向文件尾后再增加offset 個位移量. 當whence 值為SEEK_CUR 或
SEEK_END 時, 參數offet 允許負值的出現.
下列是教特別的使用方式:
1) 欲將讀寫位置移到文件開頭時:lseek(int fildes, 0, SEEK_SET);
2) 欲將讀寫位置移到文件尾時:lseek(int fildes, 0, SEEK_END);
3) 想要取得目前文件位置時:lseek(int fildes, 0, SEEK_CUR);
返回值:當調用成功時則返回目前的讀寫位置, 也就是距離文件開頭多少個字節. 若有錯誤則返回-1, errno 會存放錯誤代碼.
列:
最后需要注意的是:當使用write函數寫入數據后,再用read函數讀取數據,此時的文件指針會指向write函數的末尾,read函數無法讀取正確的數據,需要使用lseek函數調節文件指針偏移量
案列:通過讀取test文件並逆向寫入(一個字符一個字符)到out2.txt文件中需要配合linux+gcc運行
#include<stdio.h> #include<stdlib.h> #include<fcntl.h> #include<unistd.h> #include<sys/types.h> #include<string.h> #define SIZE_1 200 int main() { int fd,fd1; int len; int jen; int ln; char buf[SIZE_1];//讀取數據的緩沖區域 char buf1[SIZE_1];//存放反向字符 int i=0,j=0; fd=open("test2.txt",O_RDWR); fd1=open("out2.txt",O_RDWR); if(fd==-1||fd1==-1) { perror("error file"); exit(-1); } ln=read(fd,buf,SIZE_1); printf("ln:%d\n",ln); printf("%s",buf); for(j=-1;j>-(ln+1);j--) { lseek(fd,j,SEEK_END); read(fd,buf1,1); write(fd1,buf1,1); } close(fd); close(fd1); return 0; }