/**
* your name,
* the course number,
* the date the program was completed,
* a brief description of theprogram.
*/
#include<stdio.h>
int merge(const char*, const char*, const char*);
int main(){
int error = merge("Data1.txt","Data2.txt","Merged.txt");
if(error){
printf("Error: File merging failed\n");
} else {
printf("Success: File merged\n");
}
return error;
}
int merge(const char* n1, const char* n2, const char* n3){
FILE *in1 = fopen(n1, "r");
if(!in1){
printf("Error: Could not read file: %s\n", n1);
return 1;
}
FILE *in2 = fopen(n2, "r");
if(!in2){
fclose(in1);
printf("Error: Could not read file: %s\n", n2);
return 2;
}
FILE *out = fopen(n3, "w");
if(!out){
fclose(in1);
fclose(in2);
printf("Error: Could not write file: %s\n", n3);
return 3;
}
int num1, num2;
//until end of file
while(!feof(in1) && !feof(in2)){
//at beginning of file
if(!ftell(in1)){
fscanf(in1, "%d", &num1);
fscanf(in2, "%d", &num2);
}
if(num1 < num2){
fprintf(out, "%d\n", num1);
fscanf(in1, "%d", &num1);
} else if(num2 < num1){
fprintf(out, "%d\n", num2);
fscanf(in2, "%d", &num2);
} else {
fprintf(out, "%d\n", num1);
fprintf(out, "%d\n", num2);
fscanf(in1, "%d", &num1);
fscanf(in2, "%d", &num2);
}
}
while(!feof(in1)){
fprintf(out, "%d\n", num1);
fscanf(in1, "%d", &num1);
}
while(!feof(in2)){
fprintf(out, "%d\n", num2);
fscanf(in2, "%d", &num2);
}
fclose(out);
fclose(in1);
fclose(in2);
return 0;
}
Download
Comments
Post a Comment