C語言lseek()函數(shù)詳解
頭文件:
#include <sys/types.h> #include <unistd.h>
函數(shù)原型:
off_t lseek(int fd, off_t offset, int whence);//打開一個文件的下一次讀寫的開始位置
參數(shù):
fd 表示要操作的文件描述符
offset是相對于whence(基準(zhǔn))的偏移量
whence 可以是SEEK_SET(文件指針開始),SEEK_CUR(文件指針當(dāng)前位置) ,SEEK_END為文件指針尾
返回值:
文件讀寫指針距文件開頭的字節(jié)大小,出錯,返回-1
lsee的作用是打開文件下一次讀寫的開始位置,因此還有以下兩個作用
1.拓展文件,不過一定要一次寫的操作。迅雷等下載工具在下載文件時候先擴展一個空間,然后再下載的。
2.獲取文件大小。
lseek()函數(shù)會重新定位被打開文件的位移量,根據(jù)參數(shù)offset以及whence的組合來決定:
SEEK_SET:從文件頭部開始偏移offset個字節(jié)。
SEEK_CUR:從文件當(dāng)前讀寫的指針位置開始,增加offset個字節(jié)的偏移量。
SEEK_END:文件偏移量設(shè)置為文件的大小加上偏移量字節(jié)。
獲取文件大小
#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<0)
{
perror("open test.txt");
exit(-1);
}
printf("file size:%d \n",lseek(fd,0,SEEK_END));
close(fd);
}
拓展一個文件,一定要有一次寫操作
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void)
{
int fd=open("test.txt",O_RDWR);
if(fd<0)
{
perror("open test.txt");
exit(-1);
}
lseek(fd,0x1000,SEEK_SET);
write(fd,"a",1);
close(fd);
return 0;
}
到此這篇關(guān)于C語言lseek()函數(shù)詳解的文章就介紹到這了,更多相關(guān)C語言lseek()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c++調(diào)用python實現(xiàn)圖片ocr識別
所謂c++調(diào)用python,實際上就是在c++中把整個python當(dāng)作一個第三方庫引入,然后使用特定的接口來調(diào)用python的函數(shù)或者直接執(zhí)行python腳本,本文介紹的是調(diào)用python實現(xiàn)圖片ocr識別,感興趣的可以了解下2023-09-09
c++中關(guān)于max_element()函數(shù)解讀
這篇文章主要介紹了c++中關(guān)于max_element()函數(shù)解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02

