Linux 系統 IO之 lseek 函數
1. lseek 函數
1.1 頭文件包含
#include <sys/types.h>
#include <unistd.h>
1.2 函數原型
off_t lseek(int fd, off_t offset, int whence);
1.3 函數功能
lseek
主要用來重新定位被打開文件的位移量
根據其特性,還可以實現如下兩個功能:
- 獲取文件的大小
- 對文件進行向後擴展(文件件位置標記向後偏移 N 個字節,並且需要在 N+1 位置寫如一個數據)
1.4 函數返回值
- 返回值爲
正數 N
:表示當前文件位置標記向後移動 N 字節
- 返回值爲
複數N
: 表述當前文件位置標記向前移動 N 字節
1.5 形參解釋
int fd
:文件描述符
off_t offset
:與 whence
組合使用
int whence
:
SEEK_SET
: 將文件位置標記設置爲從頭部偏移 offset
字節 位置
SEEK_CUR
:將文件位置標記設置爲從當前位置偏移 offset
字節 位置
SEEK_END
:將文件位置標記設置爲從尾部偏移 offset
字節 位置
2. 案例程序
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int fd = open("annNote", O_RDWR);
if( -1 == fd){
perror("open file");
exit(1);
}
int ret = lseek(fd, 0, SEEK_END);
printf("file length = %d\n", ret);
ret = lseek(fd, 100, SEEK_END);
printf("return value %d\n", ret);
write(fd, "#", 1);
close(fd);
return 0;
}