Linux系统函数之lseek函数 fseek与lseek的对比 文件存放位置: 示例代码:使用lseek函数拓展文件的长度
fseek与lseek的对比
标准C库的函数# include <stdio.h> int fseek ( FILE * stream, long offset, int whence) ; Linux系统函数# include <sys/types.h> # include <unistd.h> off_t lseek ( int fd, off_t offset, int whence) ; 参数:- fd:文件描述符,通过open得到的,通过这个fd操作某个文件- offset:偏移量- whence: SEEK_SET 设置文件指针的偏移量SEEK_CUR 设置偏移量:当前位置 + 第二个参数offset的值SEEK_END 设置偏移量:文件大小 + 第二个参数offset的值返回值:返回文件指针的位置作用:1. 移动文件指针到文件头lseek ( fd, 0 , SEEK_SET ) ; 2. 获取当前文件指针的位置lseek ( fd, 0 , SEEK_CUR ) ; 3. 获取文件长度lseek ( fd, 0 , SEEK_END ) ; 4. 拓展文件的长度,当前文件10 b, 110 b, 增加了100 个字节lseek ( fd, 100 , SEEK_END ) 注意:需要写一次数据
文件存放位置:
示例代码:使用lseek函数拓展文件的长度
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <unistd.h>
# include <stdio.h> int main ( )
{ int fd = open ( "hello.txt" , O_RDWR) ; if ( fd == - 1 ) { perror ( "open" ) ; return - 1 ; } int ret = lseek ( fd, 100 , SEEK_END ) ; if ( ret == - 1 ) { perror ( "lseek" ) ; return - 1 ; } write ( fd, " " , 1 ) ; close ( fd) ; return 0 ;
}