原子操作——pread()和pwrite()


1、pread()、pwrite()函数与read()、write()函数的区别在于是否更新当前文件偏移量;

2、pread:相当于调用lseek后再调用read函数;

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

3、函数原型:

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);

4、头文件:#include <unistd.h>

5、示例:

 1 #include <stdio.h>
 2 #include <fcntl.h>
 3 #include <unistd.h>
 4 #include <sys/types.h>
 5 #include <string.h>
 6 
 7 int main(int argc,char *argv[])
 8 {
 9     int fd = open("pread.txt",O_RDWR|O_CREAT,0777);
10     int num = write(fd,"Hello World!\n",strlen("Hello World!\n"));
11     if (num < 0)
12     {
13         perror("write error!\n");
14         return -1;
15     }
16     int offset = lseek(fd,0,SEEK_CUR);
17     printf("num = %d,offset = %d\n",num,offset); // num = 13,offset = 13;
18     
19     pwrite(fd,"My Best Friends!",strlen("My Best Friends!"),6);
20     
21     char buf[20] = "",buf1[20] = "";
22     int ret = read(fd,buf,sizeof(buf));
23     if (ret < 0)
24     {
25         perror("read error!\n");
26         return -1;
27     }
28     
29     int offset1 = lseek(fd,0,SEEK_CUR);
30     printf("ret = %d,offset1 = %d\n",ret,offset1); // ret = 9,offset1 = 22;
31     
32     pread(fd,buf1,sizeof(buf1),6);
33     printf("buf = %s,buf1 = %s\n",buf,buf1);// buf =  Friends!,buf1 = My Best Friends!
34     
35     return 0;
36 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM