第二章_文件IO : 函数pread、pwrite

函数pread、pwrite

pread()、pwrite()函数与read()、write()函数的区别在于是否更新当前文件偏移量;
pread:相当于调用lseek后再调用read函数;

调用pread时,无法中断其定位和读操作,且不更新当前文件偏移量。pwrite()函数与此相同。

函数原型:

#include <unistd.h>
ssize_t pread(int fd,void *buf,size_t nbytes,off_t offset);
ssize_t pwrite(int fd,void *buf,size_t nbytes,off_t offset);

测试程序

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>

int main(int argc,char *argv[])
{
    int fd = open("pread.txt",O_RDWR|O_CREAT,0777);
    int num = write(fd,"Hello world!\n",strlen("Hello world!\n"));
    if(num<0){
        printf("write error\n");
        return -1;
    }
    int offset = lseek(fd,0,SEEK_CUR);
    printf("num = %d,offset = %d\n",num,offset); // num = 13,offset = 13;

    pwrite(fd,"My Best Friends!",strlen("My Best Friends!"),6);
    
    char buf[20]="",buf1[20]="";
    int ret = read(fd,buf,sizeof(buf));
    if(ret<0)
    {
        printf("read error!\n");
        return -1;
    }

    int offset1 = lseek(fd,0,SEEK_CUR);
    printf("ret = %d,offset1 = %d\n",ret,offset1); // ret = 9,offset1 = 22;

    pread(fd,buf1,sizeof(buf1),6);
    printf("buf = %s,buf1 = %s\n",buf,buf1);// buf =  Friends!,buf1 = My Best Friends!

    return 0;
}

在这里插入图片描述
如果用write和read则不会取修改文件的偏移量
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值