先来介绍pread函数

[root@bogon mycode]# cat test.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
char buf[20];
void testpread(int fd1)
{
int i;
printf("use pread\n");
pread(fd1,buf,3,2);//起始位置为2,偏移量为3,总的意思就是从fd1文件描述符中的起始位置为2到偏移量为3的内容读取到buf中,注意执行后文件偏移量没有变动,所以下面的第一条read语句,其实位置还是开头那里
for(i=0;i<3;i++)
printf("%c",buf[i]);
read(fd1,buf,3);
for(i=0;i<3;i++)
printf("%c",buf[i]);
printf("\nuse read\n");
read(fd1,buf,3);//上一个read使得文件偏移量移动了3个位置,所以打印的是456
for(i=0;i<3;i++)
printf("%c",buf[i]);
}
int main()
{
int fd,fd1,i;
fd1=open("linux.txt",O_RDWR);//自己再加上测试是否打开成功几条语句吧,我懒得加了
testpread(fd1);
close(fd1);
return 0;
}
[root@bogon mycode]# cat linux.txt
123456
[root@bogon mycode]# gcc test.c
[root@bogon mycode]# ./a.out
use pread
345123
use read
456[root@bogon mycode]#

接着pwrite

[root@bogon mycode]# cat linux.txt
123456
[root@bogon mycode]# cat test.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
char buf[20];
char name[]="linuxfiletest";
void testpwrite(int fd1)
{
int i;
pwrite(fd1,name,5,0);//从name中取5个字节从fd1的起始0位置开始写入
read(fd1,buf,5);//pwrite不会改变文件偏移量,所以这里还是从头开始打印的
for(i=0;i<5;i++)
printf("%c",buf[i]);
printf("\n");
}
int main()
{
int fd,fd1,i;
fd1=open("linux.txt",O_RDWR);
testpwrite(fd1);
close(fd1);
return 0;
}
[root@bogon mycode]# gcc test.c
[root@bogon mycode]# ./a.out
linux
[root@bogon mycode]# cat linux.txt
linux6//文件内容被修改了
[root@bogon mycode]#

最新文章

  1. e.target.files[0]层层剖析
  2. nodejs 中自定义事件
  3. codeforces 721C (拓排 + DP)
  4. Struts2中的Action类(解耦方式,耦合方式)
  5. 8.11-8.16:usaco
  6. 使用CompletionService结合ExecutorService批处理任务
  7. android app修改包名
  8. ASP.NET多用户操作相同互斥的对象
  9. android 62 手机存储目录的划分
  10. android关于图片缩放
  11. jq實現網頁個性title
  12. css颜色渐变在不同浏览器的设置
  13. svn客户端的使用
  14. UVA10256 The Great Divide
  15. Upload Files In ASP.NET Core 1.0 (Form POST And JQuery Ajax)
  16. 【LeetCode】二叉搜索树的前序,中序,后续遍历非递归方法
  17. C++ leetcode Longest Substring Without Repeating Characters
  18. date 工具类
  19. scala-05-map映射
  20. matlab中的Traing、Validation、Testing

热门文章

  1. Mac生成rsa证书
  2. ios 设置本地化显示的app名称
  3. 不同生产商的CPU以及大端/小端对齐
  4. [leetcode121]股票买卖 Best Time to Buy and Sell Kadane算法
  5. 3.3 C++改变基类成员在派生类中的访问属性
  6. final视频
  7. &lt;Using parquet with impala&gt;
  8. pytest的fixture和conftest
  9. ios手动添加数组字典(NSMutableDictionary)
  10. 获取Map的key和value的两种方法