Linux 系統 IO之 lseek 函數

Linux 系統 IO之 lseek 函數



1. lseek 函數

1.1 頭文件包含

// 因爲形參包含 off_t 類型,所以要包含 types.h
#include <sys/types.h>
#include <unistd.h>

1.2 函數原型

// off_t 用於文件大小和偏移量
// 在我的 Ubuntu 64 位系統中,本質位 long int
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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章