我正在創建一個程式來合并 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;
}
一切都很好,但我意識到我需要在新行中輸入第二個檔案的內容,而不是在第一個檔案文本的末尾。我應該對我的代碼進行哪些更改?
uj5u.com熱心網友回復:
如果第一個檔案不以換行符結尾,則應在復制第二個檔案的內容之前輸出一個。
另請注意,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("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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446362.html
