Linux系統lseek函式作用
阿新 • • 發佈:2019-01-07
首先看下函式: off_t lseek(int fd, off_t offset, int whence);
所需要標頭檔案:
#include <sys/types.h>
#include <unistd.h>
引數:
fd 表示要操作的檔案描述符
offset是相對於whence(基準)的偏移量
whence 可以是SEEK_SET(檔案指標開始),SEEK_CUR(檔案指標當前位置) ,SEEK_END為檔案指標尾
返回值:檔案讀寫指標距檔案開頭的位元組大小,出錯,返回-1
lseek 主要作用是移動檔案讀寫指標,因此還有以下兩個作用
1.拓展檔案,不過一定要一次寫的操作。迅雷等下載工具在下載檔案時候先擴充套件一個空間,然後再下載的。
2.獲取檔案大小
#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<unistd.h> #include <sys/stat.h> #include <fcntl.h> void main() { int add_len = 1024*8; int fd=open("test.txt",O_RDWR); if(fd == -1) { perror("open test.txt"); exit(-1); } lseek(fd,add_len-1,SEEK_END); write(fd,"0",1); }
執行程式後
獲取檔案長度:
#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<unistd.h> #include <sys/stat.h> #include <fcntl.h> void main() { int fd=open("test.txt",O_RDWR); if(fd == -1) { perror("open test.txt"); exit(-1); } printf("file len:%d \n",lseek(fd,0,SEEK_END)); close(fd); }