您当前的位置:网站首页>碎碎语>深度解析Linux lseek函数的使用

深度解析Linux lseek函数的使用

2023年02月02日 投稿作者:admin 围观人数:277
深度解析Linux lseek函数的使用

注:如果文章内容有误,请留言指出,谢谢合作。

名字

Name : lseek - reposition read/write file offset

lseek函数的作用是用来重新定位文件读写的位移。

头文件以及函数声明

#include#includeoff_tlseek(intfd,off_toffset,intwhence);

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#include#include#include#include#include#defineBUFFER_SIZE1024#defineSRC_FILE_NAME"src_file"#defineDEST_FILE_NAME"dest_file"//根据传入的参数来设置offset#defineOFFSET(atoi(args[1]))intmain(intargc,char*args[]){intsrc_file,dest_file;unsignedcharbuff[BUFFER_SIZE];intreal_read_len,off_set;if(argc!=2){fprintf(stderr,"Usage:%soffset\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权限:rwif(src_file

标签

深度解析Linux lseek函数的使用
版权说明
免责声明:本文文章内容由技术导航发布,但不代表本站的观点和立场,具体内容可自行甄别.