Linux系統庫函式 lseek函式用法

2021-05-23 16:56:29 字數 1095 閱讀 4801

使用 lseek 函式可以改變檔案的 cfo 。

#include

off_t lseek(int filedes, off_t offset, int whence);

返回值:新的偏移量(成功),-1(失敗)

引數 offset 的含義取決於引數 whence:

1. 如果 whence 是 seek_set,檔案偏移量將被設定為 offset。

2. 如果 whence 是 seek_cur,檔案偏移量將被設定為 cfo 加上 offset,

offset 可以為正也可以為負。

3. 如果 whence 是 seek_end,檔案偏移量將被設定為檔案長度加上 offset,

offset 可以為正也可以為負。

seek_set、seek_cur 和 seek_end 是 system v 引入的,在這之前使用的是 0、1 和 2。

lseek 的以下用法返回當前的偏移量:

off_t    currpos;

currpos = lseek(fd, 0, seek_cur);

這個技巧也可用於判斷我們是否可以改變某個檔案的偏移量。如果引數 fd(檔案描述符)指定的是 pipe(管道)、fifo 或者 socket,lseek 返回 -1 並且置 errno 為 espipe。

對於普通檔案(regular file),cfo 是乙個非負整數。但對於特殊裝置,cfo 有可能是負數。因此,我們不能簡單地測試 lseek 的返回值是否小於 0 來判斷 lseek 成功與否,而應該測試 lseek 的返回值是否等於 -1 來判斷 lseek 成功與否。

lseek 僅將 cfo 儲存於核心中,不會導致任何 i/o 操作。這個 cfo 將被用於之後的讀寫操作。

如果 offset 比檔案的當前長度更大,下乙個寫操作就會把檔案「撐大(extend)」。這就是所謂的在檔案裡創造「空洞(hole)」。沒有被實際寫入檔案的所有位元組由重複的 0 表示。空洞是否占用硬碟空間是由檔案系統(file system)決定的。

原文:http://hi.baidu.com/%ce%daѻ%c3%f7/blog/item/7ac5cc430b45501673f05d00.html

Linux系統lseek函式作用

首先看下函式 off t lseek int fd,off t offset,int whence 所需要標頭檔案 include include 引數 fd 表示要操作的檔案描述符 offset是相對於whence 基準 的偏移量 whence 可以是seek set 檔案指標開始 seek cu...

linux下 lseek函式用法

lseek函式 用法 表頭檔案 include include 定義函式 off t lseek int fildes,off t offset,int whence seek set 引數offset即為新的讀寫位置 seek cur 當前讀寫位置後增加offset個位移量。seek end 將讀...

lseek函式的用法lseek函式的用法

使用 lseek 函式可以改變檔案的 cfo include unistd.h include off t lseek int filedes,off t offset,int whence 返回值 新的偏移量 成功 1 失敗 引數 offset 的含義取決於引數 whence 1.如果 whenc...