linux pread/pwrite

        pread/pread操作是原子性的,seek和read/write操作一起完成,适合用于多线程中。

mapan@mapan-virtual-machine:~/c++$ cat test.txt 
hello world

   demo

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
   char buf[20] = {0};
   int fd = open("test.txt",O_RDWR);
   pread(fd,buf,5,2); //10表示要读的字节数,2表示偏移量
   printf("buf=%s\n",buf);

   char str[10] = "12345";
   pwrite(fd,str,3,2);//3表示要写入的字节数,2表示偏移量

   close(fd);
   return 0;
}

执行结果:

mapan@mapan-virtual-machine:~/c++$ ./a.out 
buf=llo w
mapan@mapan-virtual-machine:~/c++$ cat test.txt
he123 world
mapan@mapan-virtual-machine:~/c++$ 

 

上一篇:ubuntu中安装ssh服务


下一篇:5 - Configure External network connectivity for Virtual machine