已知2个磁盘文件如x.txt、y.txt,这两个文件中存放着已排好序的若干字符,要求将两个文件有序合并,合并后存放在文件z.txt中。
在这种情况下,可以使用归并排序的思想来合并这两个已排好序的文件。
首先,可以打开两个文件,然后分别从文件的开头开始读取字符。然后,可以比较从两个文件中读取的字符,并将小的字符写入输出文件 z.txt。接下来,可以继续从两个文件中读取字符,并重复该过程,直到两个文件中均没有字符可读为止。
例如,假设文件 x.txt 中存储的是字符 a、c、e、g,文件 y.txt 中存储的是字符 b、d、f、h,则合并后的文件 z.txt 中应包含字符 a、b、c、d、e、f、g、h。
#include <stdio.h>
int main(void) {
// Open the input files
FILE *x_file = fopen("x.txt", "r");
FILE *y_file = fopen("y.txt", "r");
// Open the output file
FILE *z_file = fopen("z.txt", "w");
// Read the first character from each file
int x_char = fgetc(x_file);
int y_char = fgetc(y_file);
// Loop until one of the files is exhausted
while (x_char != EOF && y_char != EOF) {
// Write the smaller character to the output file
if (x_char < y_char) {
fputc(x_char, z_file);
x_char = fgetc(x_file);
} else {
fputc(y_char, z_file);
y_char = fgetc(y_file);
}
}
// Write any remaining characters to the output file
while (x_char != EOF) {
fputc(x_char, z_file);
x_char = fgetc(x_file);
}
while (y_char != EOF) {
fputc(y_char, z_file);
y_char = fgetc(y_file);
}
// Close the files
fclose(x_file);
fclose(y_file);
fclose(z_file);
return 0;
}