首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言實例練習

C 語言練習範例 99:合併兩個檔案內容並排序

     編輯:C 語言實例練習

讀取 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
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved