转:基本IO函数的使用(lseek)
来源:互联网 发布:gif动态图制作软件 编辑:程序博客网 时间:2024/05/14 12:50
lseek(移动文件的读写位置)
表头文件
#include<sys/types.h>
#include<unistd.h>
定义函数: off_t lseek(int fildes,off_t offset ,int whence);
函数说明:
每一个已打开的文件都有一个读写位置,当打开文件时通常其读写
位置是指向文件开头,若是以附加的方式打开文件(如 O_APPEND)
,则读写位置会指向文件尾。当 read() 或 write()
时,读写位置会随之增加,lseek()便是用来控制该文件的读写位
置。参数 fildes 为已打开的文件描述词,参数 offset 为根据参数
whence 来移动读写位置的位移数。参数 whence 为下列其中一种:
SEEK_SET 参数 offset 即为新的读写位置。
SEEK_CUR 以目前的读写位置往后增加 offset 个位移量。
SEEK_END 将读写位置指向文件尾后再增加 offset 个位移量。
当 whence 值为 SEEK_CUR 或 SEEK_END 时,参数 offet 允许负值
的出现。
下列是教特别的使用方式:
1) 欲将读写位置移到文件开头时:lseek(int fildes,0,SEEK_SET) ;
2) 欲将读写位置移到文件尾时:lseek(int fildes,0,SEEK_END) ;
3) 想要取得目前文件位置时:lseek(int fildes,0,SEEK_CUR) ;
返回值
当调用成功时则返回目前的读写位置,也就是距离文件开头多少个
字节。若有错误则返回-1,errno 会存放错误代码。
附加说明
Linux 系统不允许 lseek()对 tty 装置作用,此项动作会令 lseek()
返回 ESPIPE。
示例程序:
运行结果:
[root@localhost src]# gcc lseek.c
[root@localhost src]# ./a.out
[root@localhost src]# cat temp.log
Hello woHello woHello woHello woHello woHello woHello woHello woHello woHello world!
/*******************************************************************************************
** Name:lseek.c
** This program is used to show the usage of lseek() .
** Author:zieckey
** Date:2007/9/29
** All rights reserved!
*******************************************************************************************/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(void)
{
int fd, i, rev;
char buf[] = "Hello world!";
fd = open( "temp.log", O_WRONLY|O_CREAT );//以可读写的方式打开一个文件,如果不存在则创建该文件
for( i=0; i<10; i++ )
{
write( fd, buf, sizeof(buf) );
lseek( fd, -5, SEEK_CUR);
}
close( fd );
return 0;
}
- 转:基本IO函数的使用(lseek)
- IO高级编程——获取特定位置上的数据(lseek函数的使用)
- (十)lseek函数的介绍和使用
- 基本IO函数的使用
- 文件IO---lseek、fcntl函数
- lseek随机读取函数的使用
- Linux 文件IO函数(open/close/read/write/lseek)
- lseek()函数的使用说明
- lseek函数的用法
- lseek函数的用法
- 基本IO函数的使用(open,write,read)
- 基本IO函数的使用(open,write,read)
- 基本IO函数的使用(open,write,read)
- lseek()函数和fseek()函数的使用详解
- IO lseek
- linux lseek函数使用感受
- 文件操作编程一(open、close、read、write、lseek函数的使用)
- open read write fcntl lseek等函数的使用整理:
- 面试中如何发现优秀的程序员
- PHP的Socket函数参考
- 客户销售策略
- 网站安全问题初探
- PHP的Socket函数参考
- 转:基本IO函数的使用(lseek)
- Andoid 编译
- 请教一条SQL查询语句
- 请问主板上元器件有什么作用
- 认识板卡上的电子元件—电阻元件介绍
- 找房子
- ORALCE热备
- 免费IT教程视频
- autoscroll与Dock属性