函数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则不会取修改文件的偏移量