c
复制代码
#include <stdio.h>
#include <stdlib.h>
//初始化变量
void initialVar(char **name1, char **name2, char **name3){
*name1 = (char*)malloc(80 * sizeof(char));
*name2 = (char*)malloc(80 * sizeof(char));
*name3 = (char*)malloc(80 * sizeof(char));
}
//输入文件名称
void inputFileName(FILE **file, char *name, int num){
printf("Enter File%d Name: ", num);
scanf("%s", name);
char *sign = '\0';
if(num == 1 || num == 2){
sign = "r";
}
if(num == 3){
sign = "w+";
}
*file = fopen(name, sign);
if(*file == NULL){
perror("Cannot open this file");
system("pause");
exit(0);
}
putchar(10);
}
//输出文件内容
void outputFile(FILE **file, int num){
printf("File%d Content: ", num);
while(!feof(*file)){
putchar(fgetc(*file));
}
putchar(10);
}
//对文件内容进行排序
void sortFile(FILE **file, int count){
char *arr = (char*)malloc(count * sizeof(char));
for(int i = 0; i < count; i++){
arr[i] = fgetc(*file);
}
rewind(*file);
char temp;
for(int i = 0; i < count; i++){
for(int j = i + 1; j < count; j++){
if(arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i = 0; i < count; i++){
fputc(arr[i], *file);
}
rewind(*file);
}
//合并两个文件内容到第三个文件
void mergeFile(FILE **file1, FILE **file2, FILE **file3){
rewind(*file1);
rewind(*file2);
int count = 0;
while(!feof(*file1)){
fputc(fgetc(*file1), *file3);
count++;
}
fclose(*file1);
while(!feof(*file2)){
fputc(fgetc(*file2), *file3);
count++;
}
rewind(*file3);
sortFile(file3, count);
outputFile(file3, 3);
fclose(*file2);
fclose(*file3);
}
//释放变量内存
void freeVar(char **name1, char **name2, char **name3){
free(*name1);
free(*name2);
free(*name3);
}
int main(){
FILE *file1 = NULL;
FILE *file2 = NULL;
FILE *file3 = NULL;
char *name1 = NULL;
char *name2 = NULL;
char *name3 = NULL;
initialVar(&name1, &name2, &name3);
inputFileName(&file1, name1, 1);
outputFile(&file1, 1);
inputFileName(&file2, name2, 2);
outputFile(&file2, 2);
inputFileName(&file3, name3, 3);
mergeFile(&file1, &file2, &file3);
freeVar(&name1, &name2, &name3);
system("pause");
return 0;
}