国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Linux > 正文

Linux lseek函數的使用詳解

2024-08-28 00:04:15
字體:
來源:轉載
供稿:網友

注:如果文章內容有誤,請留言指出,謝謝合作。

名字

Name : lseek - reposition read/write file offset

lseek函數的作用是用來重新定位文件讀寫的位移。

頭文件以及函數聲明

#include <sys/types.h>#include <unistd.h>off_t lseek(int fd, off_t offset, int whence);

offset為正則向文件末尾移動(向前移),為負數則向文件頭部(向后移)。

描述

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()函數會重新定位被打開文件的位移量,根據參數offset以及whence的組合來決定:

SEEK_SET:
  從文件頭部開始偏移offset個字節。
SEEK_CUR:
  從文件當前讀寫的指針位置開始,增加offset個字節的偏移量。
SEEK_END:
  文件偏移量設置為文件的大小加上偏移量字節。

測試代碼:

#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdlib.h>#include <stdio.h>#define BUFFER_SIZE 1024#define SRC_FILE_NAME "src_file"#define DEST_FILE_NAME "dest_file"http://根據傳入的參數來設置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權限:rw  if (src_file < 0 || dest_file < 0) {    fprintf(stderr, "Open file error!/n");    exit(1);  }  off_set = lseek(src_file, -OFFSET, SEEK_END);//注意,這里對offset取了相反數  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;}

結果解析

觀察offset以及dest_file和src_file文件的大小不難看出:程序通過lseek函數將src_file文件指針重新定位到文件末尾 + offset(注意,本程序對offset取了相反數,即文件末尾 + (-offset))處,然后從文件末尾 + offset處開始向前復制文件到dest_file中。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網之家。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安龙县| 海原县| 上犹县| 云和县| 区。| 天津市| 定兴县| 新化县| 淮北市| 张掖市| 霍林郭勒市| 庆云县| 尉犁县| 根河市| 宁国市| 乐清市| 高淳县| 昌平区| 尼玛县| 广南县| 汉川市| 新巴尔虎左旗| 青海省| 汉沽区| 安福县| 沈阳市| 柳河县| 普兰县| 尼木县| 屯门区| 南投县| 井研县| 施甸县| 海南省| 神农架林区| 双牌县| 亚东县| 栾城县| 金平| 年辖:市辖区| 玛多县|