pread和pwrite函数
2024-09-01 06:19:33
先来介绍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]#
最新文章
- e.target.files[0]层层剖析
- nodejs 中自定义事件
- codeforces 721C (拓排 + DP)
- Struts2中的Action类(解耦方式,耦合方式)
- 8.11-8.16:usaco
- 使用CompletionService结合ExecutorService批处理任务
- android app修改包名
- ASP.NET多用户操作相同互斥的对象
- android 62 手机存储目录的划分
- android关于图片缩放
- jq實現網頁個性title
- css颜色渐变在不同浏览器的设置
- svn客户端的使用
- UVA10256 The Great Divide
- Upload Files In ASP.NET Core 1.0 (Form POST And JQuery Ajax)
- 【LeetCode】二叉搜索树的前序,中序,后续遍历非递归方法
- C++ leetcode Longest Substring Without Repeating Characters
- date 工具类
- scala-05-map映射
- matlab中的Traing、Validation、Testing