在新行上合并 2 个文本文件

Merging 2 text files on a new line

我正在创建一个程序来合并 C 中的 2 个文本文件(这 2 个文件必须已经存在于系统中)

#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;
}

一切都很好,但我意识到我需要在新行中输入第二个文件的内容,而不是在第一个文件文本的末尾。我应该对我的代码应用什么更改?

如果第一个文件不是以换行符结尾,你应该在复制第二个文件的内容之前输出一个。

另请注意,c 必须定义为 int

这是修改后的版本:

#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("%79s", n1) != 1)
        return 1;

    printf("Please enter name of file input 2: ");
    if (scanf("%79s", 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;
}