lseek函数

每个打开的文件都有一个与其相关联的“当前文件偏移量”,它通常是一个非负整数,用以度量从文件开始处计算的字节数。

通常,读、写操作都从当前文件偏移量处开始,并使偏移量增加所读写的字节数。

/*
 * 测试能否对标准输入设置偏移量
*/
#include <stdio.h>
#include <unistd.h>
int main(void)
{
  if(lseek(STDIN_FILENO,0,SEEK_CUR)==-1) #lseek仅将当前的文件偏移量记录在内核中,并不引起任何I/O操作。然后该偏移量用于下一个读或写操作
      printf("cannot seek\n");
  else
      printf("seek OK\n");
  return 0;
}

测试如下:

[root@localhost tmp]# ./2.out
cannot seek
[root@localhost tmp]# ./2.out < /etc/
seek OK
[root@localhost tmp]# ./2.out < /tmp/2.c
seek OK
[root@localhost tmp]# ./2.out < /tmp/2.out
seek OK

 

创建一个具有空洞的文件

#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
#include<unistd.h>
char buf1[]="abcdegesgegewgeegsge";
char buf2[]="ABDDGEGESGEWSGEFA#TKKINEG";
#define err_sys(info)                                                        \
        {                                                                        \
                fprintf(stderr, "%s:%s\n", info, strerror(errno));                \
                return -1;                                                \
        }
int main(void)
{
  int fd;
  if ((fd=creat("file.hole", S_IRUSR|S_IWUSR|S_IXUSR))<0)
       err_sys("create error");
  if(write(fd,buf1,10)!=10)
       err_sys("buf1 write error");
  //offset now =10
  if (lseek(fd,16384,SEEK_SET)==-1)
      err_sys("lseek error");
  //offset now=16384
  if (write(fd,buf2,10)!=10)
      err_sys("buf2 write error");
  //offset now=16394
  return 0;
}

测试结果:

[root@localhost tmp]# ls -l file.hole
-rwx------. 1 root root 16394 4月   7 21:03 file.hole
[root@localhost tmp]# od -c file.hole #使用od观察该文件的内容,-c标志标识以字符方式打印输出内容
0000000   a   b   c   d   e   g   e   s   g   e  \0  \0  \0  \0  \0  \0
0000020  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0
*
0040000   A   B   D   D   G   E   G   E   S   G
0040012
[root@localhost tmp]# 
#从上述输出可以看到文件中间30个未写字节都被读成0

 

posted @ 2017-04-08 11:42  karihou  阅读(293)  评论(0)    收藏  举报