C 練習例99
問題:2つのディスクファイルAとBがあり、それぞれ1行の文字を格納しています。この2つのファイルの情報を(アルファベット順に)結合して、新しいファイルCに出力する必要があります。
プログラム分析:まずA.txtとB.txtを作成する必要があります。
A.txtファイルの内容:
123
B.txtファイルの内容:
456
プログラムのソースコード:
例
// Created by www.example.com on 15/11/9.
// Copyright © 2015年 初心者チュートリアル. All rights reserved.
//
#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その他の拡張