C 練習實例99
題目:有兩個磁片檔A和B,各存放一行字母,要求把這兩個檔中的資訊合併(按字母順序排列),輸出到一個新檔C中。
程式分析:你需要先創建 A.txt 與 B.txt。
A.txt檔內容:
123
B.txt檔內容:
456
程式源代碼:
實例
// Created by www.xuhuhu.com on 15/11/9.
//
//
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE*fa,*fb,*fc;
int i,j,k;
char str[100],str1[100];
char tem;
if((fa=fopen("A.txt","r"))==NULL) // A.txt 檔需要存在
{
printf("error: cannot open A file!\n");
exit(0);
}
fgets(str,99,fa);
fclose(fa);
if((fb=fopen("B.txt","r"))==NULL) // B.txt 檔需要存在
{
printf("error: cannot open B file!\n");
exit(0);
}
fgets(str1,100,fb);
fclose(fb);
strcat(str,str1);
for(i=strlen(str)-1;i>1;i--)
for(j=0;j<i;j++)
if(str[j]>str[j+1])
{
tem=str[j];
str[j]=str[j+1];
str[j+1]=tem;
}
if((fc=fopen("C.txt","w"))==NULL) // 合併為 C.txt
{
printf("error: cannot open C file!\n");
exit(0);
}
fputs(str,fc);
fclose(fc);
system("pause");
return 0;
}
以上實例運行輸出結果後,打開 C.txt 內容如下:
123456