Isseck 定位文件流
lseek函数:
/**/
off_t lseek(int fd, off_t offset, int whence);
参数:
fd:文件描述符
offset: 偏移量
whence:起始偏移位置: SEEK_SET/SEEK_CUR/SEEK_END
返回值:
成功:较起始位置偏移量
失败:-1 errno
应用场景:
1. 文件的“读”、“写”使用同一偏移位置。
2. 使用lseek获取文件大小 lseek( fd,0, SEEK_END);
3. 使用lseek拓展文件大小:要想使文件大小真正拓展,必须引起IO操作。
使用 truncate 函数,直接拓展文件。
int ret = truncate("dict.cp", 250);
#include "../public.h";
int main(void)
{
int fd;
char b;
char* buffer;
int n=0;
buffer = "sfjdjfs123";
fd = open("./test.txt",O_RDWR|O_CREAT,0755);
if( fd < 0 )
{
perror("open test.txt is error");
return 0;
}
write( fd , buffer ,strlen(buffer));/* 文件的读写操作都是在同一个位置 */
/* 需要在此处lseeck让文件位置到文件开头 */
lseek( fd,0,SEEK_SET );
while((n = read( fd,&b,1 )) )
{
/* n表示读入的数据 */
if( n<0 )
{
printf(" read error ");
exit(1);
}
write( STDOUT_FILENO ,&b , n );
}
close(fd);
return ;
}

浙公网安备 33010602011771号