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

一、pread()、pwrite()函數與read()、write()函數的區別在因而否更新當前文件偏移量;函數

二、pread:至關於調用lseek後再調用read函數;spa

調用pread時,沒法中斷其定位和讀操做,且不更新當前文件偏移量。pwrite()函數與此相同。code

三、函數原型:blog

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

四、頭文件:#include <unistd.h>it

五、示例:io

 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 }
相關文章
相關標籤/搜索