Linux C : lseek函数

        当我们对于文件进行操作时,不可避免的要和光标移动打交道。不像在图形化界面中使用键盘方向键甚至鼠标字节点击的操作,在Linux文件操作中,需要使用 lseek这个api进行光标偏移。

头文件:<sys/types.h>、<unistd.h>

函数原型:off_t lseek(int fd, off_t offset, int whence);

描述:将文件读写指针相对whence移动offset个字节;

fd:文件句柄;

offset: 偏移值(向后,单位byte)

whence:位置宏

返回值:如果函数调用成功,返回函数调用前后光标的偏移值

 whence的位置宏:

SEEK_SET:文件头

SEEK_CUR:当前光标位置

SEEK_END:文件尾

 demo:

int main()
{
    int fd;
    char *buf = "this is a message from linux c.";

    fd = open("./file1", O_RDWR);
    if(fd == -1)
    {
        printf("fail to open\n");
        fd = open("./file1", O_RDWR | O_CREAT, 0600);
        if(fd > 0)
        {
            printf("open succeddfully\n");
        }
    }
    printf("fd = %d\n", fd);

    int n_write = write(fd, buf, strlen(buf));
    if( n_write != -1 )
    {
        printf("write %d byte to file\n", n_write);
    }

    char *readbuf;
    readbuf = (char *)malloc(sizeof(char) * n_write + 1);

    /*这时,光标在fd的尾部,如果直接进行读取操作会什么都读不到*/

    lseek(fd, -n_write, SEEK_END);
    /*从文件尾部向前偏移n_write个字节*/

    int n_read = read(fd, readbuf, n_write);
    printf("n_read = %d\n", n_read);
    printf("form file1: %s\n", readbuf);

    close(fd);

    return 0;
}

运行结果:
fd = 3
write 31 byte to file
n_read = 31
form file1: this is a message from linux c.

此时的

lseek(fd, -n_write, SEEK_END);//文件尾向前偏移n_write个字节

也可以写成下面两种方法:

lseek(fd, 0, SEEK_SET);//直接偏移到文件头
lseek(fd, -n_write, SEEK_CUR);//当前光标位置向前偏移n_write个字节

 利用返回值计算文件的大小(上面demo一样的file1,头文件和上面的demo相同):

  1 #include <sys/types.h>
  2 #include <sys/stat.h>
  3 #include <fcntl.h>
  4 #include <stdio.h>
  5 #include <unistd.h>
  6 #include <stdlib.h>
  7 #include <string.h>
  8
  9 int main()
 10 {
 11     int fd;
 12     int filesize;
 13
 14     fd = open("./file1", O_RDWR);
 15
 16     filesize = lseek(fd, 0, SEEK_END);
 17
 18     printf("the size of file1 : %d\n", filesize);
 19
 20     close(fd);
 21
 22     return 0;
 23 }

运行结果: 

 the size of file1 : 31

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值