📅  最后修改于: 2023-12-03 15:00:13.500000             🧑  作者: Mango
本程序实现了读取两个文件的内容,然后将它们合并为第三个文件的功能。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 4) {
printf("Usage: %s <inputfile1> <inputfile2> <outputfile>\n", argv[0]);
return 1;
}
char *inputfile1 = argv[1];
char *inputfile2 = argv[2];
char *outputfile = argv[3];
FILE *ifp1 = fopen(inputfile1, "r");
FILE *ifp2 = fopen(inputfile2, "r");
FILE *ofp = fopen(outputfile, "w");
if (ifp1 == NULL || ifp2 == NULL || ofp == NULL) {
printf("Error: Cannot open file.\n");
return 1;
}
char buffer[1024];
// 读取第一个文件
while (fgets(buffer, sizeof(buffer), ifp1) != NULL) {
fputs(buffer, ofp);
}
// 读取第二个文件
while (fgets(buffer, sizeof(buffer), ifp2) != NULL) {
fputs(buffer, ofp);
}
// 关闭文件
fclose(ifp1);
fclose(ifp2);
fclose(ofp);
printf("Done.\n");
return 0;
}
gcc merge.c -o merge
./merge input1.txt input2.txt output.txt
其中,input1.txt
和input2.txt
是要合并的两个文件的路径,output.txt
是生成的第三个文件的路径。