文章目录
1 函数read
1.1 read函数原型
#include<unistd.h>
ssize_t read(int fd,void *buf,size_t nbytes);
1.2 参数说明
fd:文件描述符
buf:要读的缓冲区,通用指针。
nbytes:要读的字节数。
1.3 返回值
若成功,返回读到的字节数,若已到文件尾,返回0;若出错,返回-1。
2 函数write
2.1 write函数原型
#include<unistd.h>
ssize_t write(int fd,const void *buf,size_t nbytes);
2.2 参数说明
fd:文件描述符
buf:要写的缓冲区,通用指针。
nbytes:要写的字节数。
2.3 返回值
若成功,返回已写的字节数;若出错,返回-1。
3 函数lseek
3.1 lseek函数原型
#inlcude<unistd.h>
off_t lseek(int fd,off_t offset,int whence);
3.2 参数说明
参数offset的解释与参数whence的值有关:
- 若whence是SEEK_SET,则将该文件的偏移量设置为距文件开始处offset个字节。
- 若whence是SEEK_CUR,则将该文件的偏移量设置为其当前值加offset,offset可正可负。
- 若whence是SEEK_END,则将该文件的偏移量设置为文件长度加offset,offset可正可负。
3.3 返回值
若成功,返回新的文件偏移量;若出错,返回-1。
4 示例
问题:有文件1,其中有数据"hello word!",将文件1.txt中的"world"写入2.txt中。
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
int main(int argc,char* argv[]){
int fd1,fd2,n;
char buf[6];
fd1=open("/home/hccqxd/apue/data/1.txt",O_RDWR);
if(fd1<0)
printf("open error!");
fd2=open("/home/hccqxd/apue/data/2.txt",O_RDWR);
if(fd2<0)
printf("open error!");
lseek(fd1,6,SEEK_CUR); //将文件1的偏移量移至距开始第6个字符,也就是“w”位置
read(fd1,buf,5); //将world读至buf中
write(fd2,buf,5); //将buf中的world写入文件2
close(fd1);
close(fd2);
exit(0);
}