write()
:常用来写文件,定义如下:
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
参数含义:
fd: 文件描述符;
buf: 缓存区,存放将要写入的数据;
count: 每次写入的个数。
函数功能:
每次从buf缓存区拿count个字节写入fd文件。
返回值:
大于或等于0表示执行成功,返回写入的字节数;
返回-1代表出错。
实验代码在io/io3.c:路径为:11_Linux系统开发进阶\Linux系统编程_章节使用资料。
复制文件:使用read()度数据到缓存区,再将缓存区内容写到topeet.txt实现文件复制。
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
char buf[8]={0};
size_t rlen,wlen;
int rfd = open("./hello.txt",O_RDONLY);
int wfd = open("./topeet.txt",O_CREAT|O_RDWR);
if(-1 == rfd || -1 == wfd){
perror("open");
return -1;
}
do{//读取文件内容并写到目标文件
rlen = read(rfd,buf,sizeof(buf));
wlen = write(wfd,buf,sizeof(buf));
printf("%s",buf);
memset(buf,0,sizeof(buf));
}while(rlen>0 && wlen >=0);
printf("\n");
close(rfd);
close(wfd);
return 0;
}
编译运行打开topeet.txt :
可以看到已经完成了复制。