lseek函数实现对打开文件的定位


LSEEK

文章目录

lseek函数

  • lseek函数,定位到打开文件的指定位置处
       #include <sys/types.h>
       #include <unistd.h>

       off_t lseek(int fd, off_t offset, int whence);
  • fd文件描述符
  • offset偏移量
  • whence在何处偏移
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>


int main(int argc, char *argv[])
{

    off_t offset;
    int fd;
    ssize_t numWritten;


    fd = open(argv[1], O_RDWR | O_CREAT,
                S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
                S_IROTH | S_IWOTH);                     /* rw-rw-rw- */
    if (fd == -1)
        perror("open");

        
    offset = 10000;
    //< SEEK_SET说明是从文件头部开始偏移
    if (lseek(fd, offset, SEEK_SET) == -1)
            perror("lseek");
    printf("%s: seek succeeded\n", "10000");
    numWritten = write(fd, "abc", strlen("abc"));
    printf("write  = %ld\n", (long int)numWritten);

    if (close(fd) == -1)
        perror("close");

    exit(0);
}

  • test
$ touch tfile
$ ./seek_io tfile 
10000: seek succeeded
write  = 3
$ ls -l tfile 
-rw-rw-r-- 1 andrew andrew 10003 5月  25 23:27 tfile
  • 说明
  • 打开文件之后,从文件开始处偏移10000之后有写入3个字符,所以为10003
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Achou.Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值