C语言练习-文件读写01

C语言练习-文件读写

要求:

设在文件a.txt和文件b.txt中分别存有两个字符串,设计一个程序将这两个字符串按依序交叉的方式合并为一个字符串(例如“aaaaa”与“bbb”的合并结果为“abababaa”,而“bbb”与“aaaaa”的合作结果为“ bababaa”,)并将结果存入文件a.txt中。

分析:

首先定义两个文件指针 分别指向a和b   a以读写的方式打开,b以读的方式打开。

再定义一个新的指针 指向c文件 将a和b所读的东西,依次交错写入c中。

再次读入c中所写的东西,写入a中。

关闭a b c 所对应的文件指针  释放资源。

代码:

#include<stdio.h>
#include<stdlib.h>

main()
{
	FILE *fa;
	FILE *fb;
	FILE *fc;
	
	char fna[10],fnb[10],fnc[10];
	char ch;
	
	printf("Please input the first file name!");
	scanf("%s",fna);
	
	printf("Please input the second file name!");
	scanf("%s",fnb);
	
	printf("Please input the third file name!");
	scanf("%s",fnc);
	
	if((fa=fopen(fna,"r+"))==NULL)
	{
		printf("Cannot open the file %s!",fna);
		exit(0);
	}
	
	if((fb=fopen(fnb,"r"))==NULL)
	{
		printf("Cannot open the file %s!",fnb);
		exit(0);
	}
	
	if((fc=fopen(fnc,"w+"))==NULL)
	{
		printf("Cannot open the file %s!",fnc);
		exit(0);
	}
	

	
	while(!feof(fa))
	{
		ch=fgetc(fa);
		fputc(ch,fc);
		
		if(!feof(fb))
	    {
	    ch=fgetc(fb);
		fputc(ch,fc);
		}
	}
	
	rewind(fa);
	rewind(fc);
	
	while(!feof(fc))
	{
		ch=fgetc(fc);
		
		fputc(ch,fa);
	}
	
	fclose(fa);
	fclose(fb);
	fclose(fc);
 } 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章