所有開啟的檔案都有一個當前檔案位移量(current file offset),以下簡稱為 cfo。cfo 通常是一個非負整數,用於表明檔案開始處到檔案當前位置的位元組數。讀寫操作通常開始於 cfo,並且使 cfo 增大,增量為讀寫的位元組數。檔案被開啟時,cfo 會被初始化為 0,除非使用了O_APPEND 。
使用 lseek 函數可以改變檔案的 cfo 。
#include <unistd.h>
#include <sys/types.h>
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)決定的。
以下程式建立一個有空洞的檔案:
/* Standard C header */
#include <stdio.h>
/* Unix header */
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
char buf1[] = "abcdefghij";
char buf2[] = "ABCDEFGHIJ";
int main(void)
{
int fd, size;
if ((fd = creat("file.hole", S_IRUSR|S_IWUSR)) < 0)
{
printf("creat error\n");
return -1;
}
size = sizeof buf1 - 1;
if (write(fd, buf1, size) != size)
{
printf("buf1 write error\n");
return -1;
}
/* offset now = 10 */
if (lseek(fd, 16384, SEEK_SET) == -1)
{
printf("lseek error\n");
return -1;
}
/* offset now = 16384 */
size = sizeof buf2 - 1;
if (write(fd, buf2, size) != size)
{
printf("buf2 write error\n");
return -1;
}
/* offset now = 16394 */
return 0;
}
摘自: http://apps.hi.baidu.com/share/detail/30893139