在写代码之前,先介绍一个函数作为代码铺垫:
read函数理解: ssize_t read(int fd, void *buf, size_t count);
fd:文件描述符,用来指向要操作的文件的文件结构体;
buf:一块内存空间;
count:希望读取的字节数.
具体实现代码如下:
makefile:
.PHONY:all
all : r_file r_fifo
r_file : r_file.c
gcc - o $@ $ ^
r_fifo : r_fifo.c
gcc - o $@ $ ^
.PHONY:clean
clean :
rm - f r_file r_fifo
r_file.c : (读取文件file,写入命名管道)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAX 1024
int main()
{
mkfifo("fifo",0644);//创建命名管道
//读端
int infd;
infd=open("file",O_RDONLY);//把file文件以只读方式打开
if(infd==-1)//读取失败
{
perror("open");
exit(1);
}
//写端
int outfd;
outfd=open("fifo",O_WRONLY);//把fifo以只写方式打开
if(outfd==-1)
{
perror("open");
exit(1);
}
char buf[MAX];
int s;
while (s = (read(infd, buf, MAX))>0)
//将文件描述符infd中的字节读取到缓冲区buf
//read返回成功读取到的字节数
{
write(outfd,buf,s);
// write返回:若成功则返回写入的字节数,若出错则返回-1
//write尝试将缓冲区buf中的字节写到文件描述符outfd中
}
close(infd);//关闭读端
close(outfd);//关闭写端
return 0;
}
r_fifo.c : (读取管道,写入目标文件file.txt)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAX 1024
int main()
{
//写端
int outfd;
outfd=open("file.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);//让file.txt文件以写方式创建,并且
从文件的最开始去写
if(outfd==-1)//创建失败时,则退出
{
perror("open");
exit(1);
}
//读端
int infd;
infd=open("fifo",O_RDONLY);
if(infd==-1)
{
perror("open");
exit(1);
}
char buf[MAX];
int s;
//将从管道中读取到的数据写入文件file.txt中
while ((s = read(infd, buf, MAX))>0)
{
write(outfd,buf,s);
}
//关闭读写端
close(infd);
close(outfd);
return 0;
}
程序运行结果:
首先运行r_file,将文件file中的内容读取到管道中,然后进行进程等待:
然后运行r_fifo,将管道中的数据写入目标文件file.txt中,从而实现文件的拷贝: