首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >1.23 lseek函数

1.23 lseek函数

作者头像
全栈程序员站长
发布2022-09-12 12:46:58
发布2022-09-12 12:46:58
4980
举报

大家好,又见面了,我是你们的朋友全栈君。

代码语言:javascript
复制
//标准C库函数
#include <stdio.h>
int fseek(FILE *stream, long offset, int whence);


//linux系统函数
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);

    参数:
        -fd:文件描述符
        -offset:偏移量
        -whence:
            SEEK_SET
                设置文件指针的偏移量,为文件起始地址
            SEEK_CUR
                设置文件指针的偏移量,为当前位置+第2个参数offset的值
            SEEK_END
                设置文件指针的偏移量,为文件大小+第2个参数offset的值
    返回值:返回文件指针的位置

作用:
    1.移动文件指针到文件头:               lseek(fd, 0, SEEK_SET);
    2.获取当前文件指针的位置:             lseek(fd, 0, SEEK_CUR);
    3.获取文件长度:                      lseek(fd, 0, SEEK_END);
    4.拓展文件的长度,如增加100字节:       lseek(fd, 100, SEEK_END);
     注意:拓展文件后需要写一次数据

例子:

代码语言:javascript
复制
//perror
#include <stdio.h>
//open
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

//lseek/write
#include <unistd.h>

int main()
{
    int fd=open("hello.txt", O_RDWR);
    if(fd==-1)
    {
        perror("open");
        return -1;
    }

    int ret=lseek(fd,100,SEEK_END);
    if(ret==-1)
    {
        perror("lseek");
        return -1;
    }
    //写入一个空格
    write(fd," ",1);

    close(fd);
    return 0;

}

参考:牛客网 C++高薪求职项目《Linux高并发服务器开发》1.23 lseek函数

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/149456.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档