C语言文件连接DEMO

【FROM C语言实战500例  ---39例】


#include <stdio.h>
#include <conio.h>
#include <process.h>
/*去掉程序中的warning information*/
#pragma warning(disable:4996)
/*输出文件内容*/
void OutputFile(FILE *fp)
{
	char ch;
	while((ch=fgetc(fp))!=EOF)
	{
		putchar(ch);
	}
	_getch();
}

/*文件连接函数*/
void JoinFile(char *sfilename,char *dfilename)
{
	char ch;
	FILE *fp1,*fp2;
	int err;
	/*进行输入重定向*/
	if ((err=freopen_s(&fp1,sfilename,"r",stdin))!=0)
	{
		printf("cannot open the file: %s\n",sfilename);
		return;
	}
	/*进行输出重定向*/
	if ((err=freopen_s(&fp2,dfilename,"a",stdout))!=0)
	{
		printf("cannot open the file: %s\n",dfilename);
		return 0;
	}
	/*进行文件的读写*/
	while((ch=getchar())!=EOF)
	{
		putchar(ch);
	}
	fclose(fp1);
	fclose(fp2);
	return;
}

int main(void)
{
	char sfilename[20];
	char dfilename[20];
	FILE *sfp,*dfp;
	int err;
	system("cls");
	printf("**********************************************\n");
	printf("|  The program will join a file to another!  |\n");
	printf("|You can open the object file to verify this!|\n");
	printf("**********************************************\n");
	/*得到要被连接的文件名*/
	printf("\nPlease input source filename:\n");
	gets(sfilename);

	/*得到要连接到的文件的文件名*/
	printf("Please input destination filename:\n");
	gets(dfilename);

	/*输出连接前文件的内容*/
	if(((err=fopen_s(&sfp,sfilename,"r"))!=0)||((err=fopen_s(&dfp,dfilename,"r"))!=0))
		return 0;
	printf("\nThe text of the file %s before joining :\n",sfilename);
	OutputFile(sfp);
	printf("\nThe text of the file %s before joining :\n",dfilename);
	OutputFile(dfp);
	printf("\nPlease open the file %s to verify the text!\n",dfilename);
	_getch(); /* read a single character from the console without echoing the character*/
	/*连接两个文件*/
	JoinFile(sfilename,dfilename);
	fclose(sfp);
	fclose(dfp);
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值