I’m creating a program to merge 2 text files in C (these 2 files must have already exist in the system)
#include <stdio.h>
#include <stdlib.h>
int main() {
char c;
char n1[10], n2[10];
FILE *f1, *f2, *f3;
printf("Please enter name of file input 1: ");
scanf("%s", n1);
f1 = fopen(n1, "r");
printf("Please enter name of file input 2: ");
scanf("%s", n2);
f2 = fopen(n2, "r");
f3 = fopen("question_bank.txt", "w");
if (f1 == NULL || f2 == NULL || f3 == NULL) {
printf("Error");
return 1;
}
while ((c = fgetc(f1)) != EOF) {
fputc(c, f3);
}
while ((c = fgetc(f2)) != EOF) {
fputc(c, f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
return 0;
}
Everything is pretty ok but I realise that I need to enter the second file’s content on a new line, not at the end of the first file’s text. What change should I apply to my code?
>Solution :
If the first file does not end with a newline character, you should output one before copying the contents of the second file.
Note also that c must be defined as int.