解决思路:
1、创建有名管道文件(mkfifo);
2、打开文件,读取内容到缓冲区,把缓冲区的内容写道管道(open,read,write);
3、打开(或新建)文件,读取管道中的内容到缓冲区、把缓冲区的内容写到文件中(open,read,write);
4、关闭文件,关闭管道文件
1、创建有名管道文件(mkfifo);
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
int ret = mkfifo("./myfifo",0777);
if(-1 == ret)
{
perror("mkfifo");
return -1;
}
printf("mkfifo success.\n");
return 0;
}
2、打开文件,读取内容到缓冲区,把缓冲区的内容写道管道(open,read,write);
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <strings.h>
#include <unistd.h>
#define SIZE 128
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("pleasr enter %s filename.\n",argv[0]);
return -1;
}
int ret_read = 0;
int ret_fifo = 0;
char buf[SIZE] = {0};
int fd_src = open(argv[1],O_RDONLY);
if(-1 == fd_src)
{
perror("open");
return -1;
}
int fd_fifo = open("./myfifo",O_WRONLY);
if(-1 == fd_fifo)
{
perror("open");
return -1;
}
while(1)
{
bzero(buf,sizeof(buf));
ret_read = read(fd_src,buf,sizeof(buf));
if(-1 == ret_read)
{
perror("read");
break;
}
if(0 == ret_read)
{
break;
}
write(fd_fifo,buf,ret_read);
}
close(fd_src);
close(fd_fifo);
return 0;
}
3、打开(或新建)文件,读取管道中的内容到缓冲区、把缓冲区的内容写到文件中(open,read,write);
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <strings.h>
#include <unistd.h>
#define SIZE 128
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("pleasr enter %s filename.\n",argv[0]);
return -1;
}
char buf[SIZE] = {0};
int fd_dest = open(argv[1],O_WRONLY | O_CREAT | O_TRUNC,0777);
if(-1 == fd_dest)
{
perror("open");
return -1;
}
int fd_fifo = open("./myfifo",O_RDONLY);
if(-1 == fd_fifo)
{
perror("open");
return -1;
}
int ret_read_fifo = 0;
int ret_write_dest = 0;
while(1)
{
bzero(buf,sizeof(buf));
ret_read_fifo = read(fd_fifo,buf,sizeof(buf));
if(-1 == ret_read_fifo)
{
perror("read");
break;
}
if(0 == ret_read_fifo)
{
break;
}
write(fd_dest,buf,ret_read_fifo);
}
close(fd_dest);
close(fd_fifo);
return 0;
}