1. 程式人生 > 其它 >有兩個磁碟檔案A和B,各自存放一行字母,今要求把這兩個檔案中的資訊合併(按字母順序排序),輸出到一個新檔案C中去

有兩個磁碟檔案A和B,各自存放一行字母,今要求把這兩個檔案中的資訊合併(按字母順序排序),輸出到一個新檔案C中去

技術標籤:C語言

有兩個磁碟檔案A和B,各自存放一行字母,今要求把這兩個檔案中的資訊合併(按字母順序排序),輸出到一個新檔案C中去

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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

void file(char f[])
{
	FILE *fp;
	char ch,file[10];
	printf("請輸入檔案的名字:"
); scanf("%s",file); getchar(); if((fp=fopen(file,"wb"))==NULL) { printf("can not open file\n"); exit(0); } printf("請輸入一個準備儲存到磁碟的字串(以#結束):"); ch=getchar(); while(ch!='#') { fputc(ch,fp); putchar(ch); ch=getchar(); } fclose(fp); } int main
() { FILE *fp1,*fp2,*fp3; char ch,t,filename1[10],filename2[10],filename3[10],c[200]; int a,b,i,j,n=0; printf("Please enter the name of file:"); scanf("%s",filename1); printf("Now is the %s file!\n",filename1); file(filename1); printf("\n"); printf
("Please enter the name of file:"); scanf("%s",filename2); printf("Now is the %s file!\n",filename2); file(filename2); if((fp1=fopen(filename1,"rb"))==NULL) { printf("can not open file\n"); exit(0); } printf("%s contest are:",filename1); for(i=0;(ch=fgetc(fp1))!=EOF;i++) { c[i]=ch; putchar(c[i]); n++; } fclose(fp1); i=n; if((fp2=fopen(filename2,"rb"))==NULL) { printf("can not open file\n"); exit(0); } printf("\n"); printf("%s contest are:",filename2); for(;(ch=fgetc(fp2))!=EOF;i++) { c[i]=ch; putchar(c[i]); } fclose(fp2); n=i; //排序 for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { a=c[i]; b=c[j]; if(a>b) { t=c[i]; c[i]=c[j]; c[j]=t; } } } printf("\n"); printf("Please enter the name of file:"); scanf("%s",filename3); getchar(); printf("Now is the %s file!\n",filename3); if((fp3=fopen(filename3,"wb"))==NULL) { printf("can not open file\n"); exit(0); } for(i=0;i<n;i++) { putc(c[i],fp3); putchar(c[i]); } fclose(fp3); return 0; }

這是我自己在寫這道題時的做法,我知道有很多的不足,希望可以幫到你一點,如果你有更好的辦法,可以指出來哦!