使用有名管道在不同进程间复制文件

本文介绍了一种利用有名管道实现文件数据传输的方法。通过两个程序分别作为复制端和粘贴端,实现了从源文件到目标文件的数据完整复制。复制端负责打开文件并将其内容写入有名管道;粘贴端则负责从有名管道读取数据并写入新的目标文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 复制端,打开文件,并将文件中数据
写入管道文件中

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define cpy "/tmp/cpy"

int main(int argc, char const *argv[])
{  
	ssize_t nread_file;
	ssize_t nwrite_fifo; 
    int i = 0;

	mkfifo(cpy,0777);
	/*创建有名管道*/
	int fd_fifo = open(cpy,O_RDWR);
	/*以可读可写打开有名管道*/
	int fd_file = open("1.pdf",O_RDWR);
	/*以可读可写打开文件*/
	char buf[1024] = {0};

	while(1)
	{
		memset(buf,0,sizeof(buf));
		 /*清空数组*/
		nread_file = read(fd_file,buf,sizeof(buf));
		/*读取文件*/
	    nwrite_fifo = write(fd_fifo,buf,nread_file);
	    /*将文件写入管道*/
	    if (nread_file<1024)
	    {/*如果读取少于1024,则到末尾,退出循环*/
	    	break;
	    }
	}
	printf("写入完成\n");
	
	return 0;
}

粘贴端,打开管道,并将管道中数据
写入目标文件中

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define cpy "/tmp/cpy"

int main(int argc, char const *argv[])
{  
	ssize_t nread_fifo; 
	ssize_t nwrite_file;
    int i = 0;

	mkfifo(cpy,0777);
	/*创建有名管道*/
	int fd_fifo = open(cpy,O_RDWR);
	/*以可读可写打开有名管道*/
	int fd_file_p = open("2.pdf",O_RDWR|O_CREAT,0777);
	/*以可读可写打开文件,如果文件不存在则创建文件*/
	char buf[1024] = {0};

	while(1)
	{
		memset(buf,0,sizeof(buf));
	    /*清空数组*/
	    nread_fifo = read(fd_fifo,buf,sizeof(buf));
	    /*从管道中读取数据*/
	    nwrite_file = write(fd_file_p,buf,nread_fifo);
	    /*将数据写入新的文件中*/
	    if (nread_fifo < 1024)
		{/*如果读取少于1024,则到末尾,退出循环*/
			break;
		}
	    i++;
	}
	printf("复制完成\n");
	printf("一共复制%d次,共计%d字节\n",i,i*1024);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值