【输入形式】
源文件名和目标文件名在执行时作为程序命令行参数输入,例如若程序名为sort,
源文件名和目标文件名分别为sort.in和sort.out,则命令行为:sort sort.in sort.out。
程序将从当前目录下sort.in文件中读入单词。
【输出形式】
对单词进行排序,删除重复出现的单词,然后将结果输出到文件sort.out中。
【输入样例】
假如sort.in文件内容如下:
rrr sss aaa bbb ccc ddf aaa dd
【输出样例】
sort.out文件内容为:
aaa bbb ccc dd ddf rrr sss
【样例说明】
读入文件sort.in,做适当的排序,并删除重复出现的单词,输出到文件sort.out
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
typedef struct word
{
char words[32];
int count;
struct word *next;
}WORD;
/
//对链表中的单词进行排序,采用的是冒泡排序算法
void sort(WORD *head)
{
char str[32];
int n;
WORD *p;
WORD *p2;
for (p = head;p != NULL;p = p->next)
for (p2 = p;p2 != NULL;p2 = p2->next)
{
//if (p2->count > p->count)
if(memcmp(p2->words,p->words,32)<0)
{
strcpy(str, p->words);
n = p->count;
strcpy(p->words, p2->words);
p->count = p2->count;
strcpy(p2->words, str);
p2->count = n;
}
}
}
int fun(FILE *in, FILE *out)
{
int yes = 1;
char ch;
WORD *head = NULL;
WORD *p;
WORD *temp;
char str[128];
int i = 0;
if (!(in && out))
{
printf("文件打开或建立失败!");
getch();
}
while (!feof(in))
{
memset(str, 0, 32);
while (!feof(in))
{
ch = fgetc(in);
if (ch != 32 && ch != '\n')
{
str[i++] = ch;
yes = 0;
}
else
{
if (yes != 1)
{
str[i] = '\0';
i = 0;
yes = 1;
break;
}
}
}
if (strlen(str) >= 2)
{
temp = head;
while (temp != NULL)
{
if (!(strcmp(temp->words, str)))
{
temp->count++;
break;
}
temp = temp->next;
}
if (temp == NULL)
{
p = (WORD*)malloc(sizeof(WORD));
p->next = head;
head = p;
memset(p->words, 0, 32);
strcpy(p->words, str);
p->count = 0;
}
}
}
sort(head);
while (head != NULL)
{
fprintf(out, "%-10s%d\n", head->words, head->count);
head = head->next;
}
return 0;
}
main()
{
FILE *in, *out;
in = fopen("in.txt", "r");
out = fopen("out.txt", "w");
fun(in, out);
}