书中只实现了单词内部的排序而求得标记词,而并未实现单词之间的排序,所以运行结果按不符合作者预期结果,可能是作者的一个疏忽。
完善后代码如下:
#include <stdio.h>
#include <string.h>
#define WORD_MAX_LENGTH 100
#define DICT_NUM 100
char word[DICT_NUM][WORD_MAX_LENGTH], word_sign[DICT_NUM][WORD_MAX_LENGTH], old_word_sign[WORD_MAX_LENGTH];
int count = 0;
int char_cmp(char *x, char *y)
{
return *x - *y;
}
int str_compare(char *x, char *y )
{
return strcmp(x,y);
}
int sign_and_sort(char *input_file_name, char *output_file_name)
{
FILE *fp_input, *fp_output;
int i = 0;
if ((fp_input = fopen(input_file_name, "r")) == NULL || (fp_output = fopen(output_file_name, "w")) == NULL)
{
printf("cannot access the file!");
exit(0);
}
while (fscanf(fp_input, "%s", word[count]) != EOF)
{
strcpy(word_sign[count], word[count]);
qsort(word_sign[count], strlen(word_sign[count]),sizeof(char), char_cmp);
strcat(word_sign[count], ": ");
strcat(word_sign[count], word[count]);
count++;
}
qsort(word_sign, count,sizeof(word_sign[count]), str_compare);
for (i = 0;i < count; i++)
fprintf(fp_output,"%s\n", word_sign[i]);
fclose(fp_input);
fclose(fp_output);
return 0;
}
int squash(char *input_file_name, char *output_file_name)
{
FILE *fp_input, *fp_output;
int linenumber = 0;
count = 0;
strcpy(old_word_sign, "");
if ((fp_input = fopen(input_file_name, "r")) == NULL || (fp_output = fopen(output_file_name, "w")) == NULL)
{
printf("cannot access the file!");
exit(0);
}
while (fscanf(fp_input, "%s %s", word_sign[count], word[count]) != EOF)
{
if (strcmp(old_word_sign, word_sign[count]) != 0 && linenumber > 0)
fprintf(fp_output, "\n");
strcpy(old_word_sign, word_sign[count]);
linenumber++;
fprintf(fp_output, "%s ", word[count++]);
}
fclose(fp_input);
fclose(fp_output);
return 0;
}
int main()
{
sign_and_sort("dict.txt", "mid.txt");
squash("mid.txt", "result.txt");
return 0;
}
运行过程及结果: