码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-11-11 21:47:44      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:font   turn   偏移量   bytes   nbsp   class   types   pen   bsp   

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 }

 

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

标签:font   turn   偏移量   bytes   nbsp   class   types   pen   bsp   

原文地址:https://www.cnblogs.com/ys6738-4271-3931/p/11838391.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!