pread介绍

1.先来介绍pread函数

[root@bogon mycode]# cat test.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
char buf[20];
void testpread(int fd1)
{
    int i;
    printf("use pread\n");
    pread(fd1, buf, 3, 2);//起始位置为2,偏移量为3,总的意思就是从fd1文件描述符中的起始位置
                          //为2到偏移量为3的内容读取到buf中,注意执行后文件偏移量没有变动,
                          //所以下面的第一条read语句,起始位置还是开头那里
    for (i=0; i<3; i++) 
        printf("%c", buf[i]);
    read(fd1, buf, 3);
    for (i=0; i<3; i++)
        printf("%c", buf[i]);
    printf("\nuse read\n");
    read(fd1, buf, 3); //上一次read使得文件偏移量移动了3个位置,所以打印的是456
    for (i=0; i<3; i++) 
        printf("%c", buf[i]);
}

int main()
{
    int fd, fd1, i;
    fd1 = open("linux.txt", O_RDWR);
    testpread(fd1);
    close(fd1);
    return 0;
}
[root@bogon mycode]# cat linux.txt
123456
[root@bogon mycode]# gcc test.c
[root@bogon mycode]# ./a.out
use pread
345123
use read
456
[root@bogon mycode]#

2.再介绍pwrite

[root@bogon mycode]# cat linux.txt
123456
[root@bogon mycode]# cat test.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
char buf[20];
char name[] = "linuxfiletest";
void testpwrite(int fd1)
{
    int i;
    pwrite(fd1, name, 5, 0);//从name中取5个字节从fd1的起始0位置开始写入
    read(fd1, buf, 5);//pwrite不会改变文件偏移量,所以这里还是从头开始打印的
    for (i=0; i<5; i++) 
        printf("%c", buf[i]);
    printf("\n");
}
int main()
{
    int fd, fd1, i;
    fd1 = open("linux.txt", O_RDWR);
    testpwrite(fd1);
    close(fd1);
    return 0;
}
[root@bogon mycode]# gcc test.c
[root@bogon mycode]# ./a.out
linux
[root@bogon mycode]# cat  linux.txt
linux6//文件内容被修改了
[root@bogon mycode]#

参考链接:https://blog.csdn.net/qq_34829953/article/details/72725406

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值