zoukankan      html  css  js  c++  java
  • lseek系统调用

    文件的随机读写。目前为止,文件都是顺序访问。读写都是从当前文件的偏移位置开始,然后文件偏移值自动的增加到刚好超出读或者写结束的位置
    是它为下一次作好准备。在linux中有文件偏移。使得随机访问变得简单,只需将当前文件位置移植到有关位置,将迫使read()或write()函数发生在这一位置,
    除非文件被O_APPEND打开,在这种情况下,write()调用然将在结尾
    lseek 对应于 c库中的 fseek
    off_t lseek(int fd,off_t offset, int base) 当调用成功时则返回目前的读写位置,也就是距离文件开头多少个字节。若有错误则返回-1,errno 会存放错误代码
    offset:偏移量  base:偏移起始位置(文件头(SEEK_SET)开始偏移,当前指针位置开始偏移(SEEK_CUR),文件尾(SEEK_END))unistd.h

     1 #include <sys/types.h>
     2 #include <sys/stat.h>
     3 #include <fcntl.h>
     4 #include<errno.h>
     5 #include<unistd.h>
     6 #include<stdio.h>
     7 #include<stdlib.h>
     8 #include<string.h>
     9 //#define ERR_EXIT(m)  (perror(m),exit(EXIT_FAILURE))
    10 #define ERR_EXIT(m)
    11     do
    12     {
    13         perror(m);
    14         exit(EXIT_FAILURE);
    15     }while(0)  //宏要求一条语句
    16 int main(void)
    17 {
    18     int fd;
    19     fd=open("test.txt",O_RDONLY);  //test.txt中ABCDE
    20     if(fd==-1)
    21         ERR_EXIT("open error");
    22     char buf[1024]={0};
    23     int ret=read(fd,buf,5);
    24     printf("buf=%s
    ",buf);
    25     if(ret==-1)
    26         ERR_EXIT("read error");
    27     ret=lseek(fd,0,SEEK_CUR); //成功返回目前偏移位置,可以通过这种方式获取当前文件偏移位置。
    28     if(ret==-1)
    29         ERR_EXIT("lseek error");
    30     printf("current seek point %d
    ",ret); //5
    31     return 0;
    32 }
  • 相关阅读:
    Swift
    Swift
    UVa
    Go如何发送广播包
    人迹罕至的android要完全退出程序的一种方法
    备注ocp_ORACLE专题网络
    JS它DOM
    HDU 1693 Eat the Trees 插头DP
    ubuntu-14.04 系统安装mysql-5.6.21
    1941设置站点模板,一生珍藏,所有玩具
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/8280566.html
Copyright © 2011-2022 走看看