Linux学习文件阶段中 lseek API的相关介绍

文件描述符的相关介绍可以去:
链接: https://blog.csdn.net/m0_52983689/article/details/113832017.

下面展示一些 内联代码片

off_t lseek(int fd,off_t offest,int whence)
fd:文件描述符
offest:对whence的一个偏移值
whence:
SEEK_SET 指向文件的头	SEEK_END 指向文件的尾	SEEK_CUR 文件的当前位置
返回值:成功返回0,失败返回-1,可以用perror()函数查看错误。
/**********************可以用来计算文件的大小**********************/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main()
{
        int fd;
        char *buf="You Matter!";
//      int open(const char *pathname, int flags);
//      int open(const char *pathname, int flags, mode_t mode);

        fd = open("./file1",O_RDWR);

        int filesize = lseek(fd,0,SEEK_END);
        printf("The file size is %d byte\n",filesize);

        close(fd);
        return 0;
}
/********************可以用来移动光标,为读文件做准备********************/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main()
{
        int fd;
        char *buf="You Matter!";
        char *readbuf;

        fd = open("./file1",O_RDWR);

        printf("fd = %d\n",fd);

        if(fd == -1){
                printf("open file error!\n");
                fd=open("./file1",O_RDWR|O_CREAT,0600);
                if(fd > 0){
                        printf("Creating a successful!\n");
                }
        }

        printf("fd = %d\n",fd);

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

        readbuf=(char *)malloc(sizeof(char)+1);
        lseek(fd,0,SEEK_SET);

        int n_read=read(fd,readbuf,n_write);
        if(n_read!=-1){
                printf("read %d byte,content is %s\n",n_read,readbuf);
        }else{
                printf("read error!\n");
        }

        close(fd);
        return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值