新聞中心
這篇文章給大家介紹如何在Linux中使用lseek函數(shù),內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
成都創(chuàng)新互聯(lián)公司為企業(yè)級(jí)客戶提高一站式互聯(lián)網(wǎng)+設(shè)計(jì)服務(wù),主要包括成都做網(wǎng)站、成都網(wǎng)站建設(shè)、重慶APP軟件開(kāi)發(fā)、成都小程序開(kāi)發(fā)、宣傳片制作、LOGO設(shè)計(jì)等,幫助客戶快速提升營(yíng)銷能力和企業(yè)形象,創(chuàng)新互聯(lián)各部門都有經(jīng)驗(yàn)豐富的經(jīng)驗(yàn),可以確保每一個(gè)作品的質(zhì)量和創(chuàng)作周期,同時(shí)每年都有很多新員工加入,為我們帶來(lái)大量新的創(chuàng)意。
lseek函數(shù)的作用是用來(lái)重新定位文件讀寫的位移。
頭文件以及函數(shù)聲明
#include#include off_t lseek(int fd, off_t offset, int whence);
offset為正則向文件末尾移動(dòng)(向前移),為負(fù)數(shù)則向文件頭部(向后移)。
描述
lseek() repositions the file offset of the open file description associated with the file descriptor fd to the argument offset according to the directive whence as follows:
SEEK_SET The file offset is set to offset bytes.
SEEK_CUR The file offset is set to its current location plus offset bytes.
SEEK_END The file offset is set to the size of the file plus offset bytes.
lseek() allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a “hole”) return null bytes (‘\0') until data is actually written into the gap.
lseek()函數(shù)會(huì)重新定位被打開(kāi)文件的位移量,根據(jù)參數(shù)offset以及whence的組合來(lái)決定:
SEEK_SET:
從文件頭部開(kāi)始偏移offset個(gè)字節(jié)。
SEEK_CUR:
從文件當(dāng)前讀寫的指針位置開(kāi)始,增加offset個(gè)字節(jié)的偏移量。
SEEK_END:
文件偏移量設(shè)置為文件的大小加上偏移量字節(jié)。
測(cè)試代碼:
#include#include #include #include #include #include #define BUFFER_SIZE 1024 #define SRC_FILE_NAME "src_file" #define DEST_FILE_NAME "dest_file" //根據(jù)傳入的參數(shù)來(lái)設(shè)置offset #define OFFSET (atoi(args[1])) int main(int argc, char*args[]) { int src_file, dest_file; unsigned char buff[BUFFER_SIZE]; int real_read_len, off_set; if (argc != 2) { fprintf(stderr, "Usage: %s offset\n", args[0]); exit(-1); } src_file = open(SRC_FILE_NAME, O_RDONLY); dest_file = open(DEST_FILE_NAME, O_WRONLY | O_CREAT, S_IREAD | S_IWRITE );//owner權(quán)限:rw if (src_file < 0 || dest_file < 0) { fprintf(stderr, "Open file error!\n"); exit(1); } off_set = lseek(src_file, -OFFSET, SEEK_END);//注意,這里對(duì)offset取了相反數(shù) printf("lseek() reposisiton the file offset of src_file: %d\n", off_set); while((real_read_len = read(src_file, buff, sizeof(buff))) > 0) { write(dest_file, buff, real_read_len); } close(dest_file); close(src_file); return 0; }
結(jié)果解析
觀察offset以及dest_file和src_file文件的大小不難看出:程序通過(guò)lseek函數(shù)將src_file文件指針重新定位到文件末尾 + offset(注意,本程序?qū)ffset取了相反數(shù),即文件末尾 + (-offset))處,然后從文件末尾 + offset處開(kāi)始向前復(fù)制文件到dest_file中。
關(guān)于如何在Linux中使用lseek函數(shù)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
文章標(biāo)題:如何在Linux中使用lseek函數(shù)
URL標(biāo)題:http://www.ef60e0e.cn/article/pjdjjo.html