Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merging 2 text files on a new line

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading