pread和pwrite函数

先来介绍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]# 

接着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]#