Home > Software engineering >  Merging 2 text files on a new line
Merging 2 text files on a new line

Time:03-18

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?

CodePudding user response:

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.

Here is a modified version:

#include <errno.h>
#include <stdio.h>
#include <string.h>

int main() {
    int c, last = 0;
    char n1[80], n2[80];
    FILE *f1, *f2, *f3;

    printf("Please enter name of file input 1: ");
    if (scanf("ys", n1) != 1)
        return 1;

    printf("Please enter name of file input 2: ");
    if (scanf("ys", n2) != 1)
        return 1;

    f1 = fopen(n1, "r");
    if (f1 == NULL) {
        fprintf(stderr, "Cannot open %s: %s\n", n1, strerror(errno));
        return 1;
    }
    f2 = fopen(n2, "r");
    if (f2 == NULL) {
        fprintf(stderr, "Cannot open %s: %s\n", n2, strerror(errno));
        return 1;
    }
    f3 = fopen("question_bank.txt", "w");
    if (f3 == NULL) {
        fprintf(stderr, "Cannot open %s: %s\n", "question_bank.txt", strerror(errno));
        return 1;
    }

    while ((c = fgetc(f1)) != EOF) {
        last = c;
        fputc(c, f3);
    }
    if (last != '\n') {
        fputc('\n', f3);
    }
    while ((c = fgetc(f2)) != EOF) {
        fputc(c, f3);
    }
    fclose(f1);
    fclose(f2);
    fclose(f3);
    return 0;
}
  • Related