讀取 A.txt、B.txt 各一行字元,合併後依字元序排序,寫入 C.txt。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fa, *fb, *fc;
char str[100], str1[100], tem;
int i, j, k;
if ((fa = fopen("A.txt", "r")) == NULL) { printf("error: cannot open A file!\\n"); exit(0); }
fgets(str, 99, fa); fclose(fa);
if ((fb = fopen("B.txt", "r")) == NULL) { 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) { printf("error: cannot open C file!\\n"); exit(0); }
fputs(str, fc); fclose(fc);
system("pause");
return 0;
}
A.txt: 123 B.txt: 456 C.txt: 123456