#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<malloc.h>
#include<ctype.h>
#define WS " ,\t!:;.-"
#define MAX_STR_LEN 1024
int i;
struct listNode {
int count;
char *word;
struct listNode *next;
} //Definition of a structure
struct listNode *newListNode(const char * const);
void insertWord(struct listNode *,const char * const);
void printList(struct listNode *);
int countlist(struct listNode *);
int main(int argc, char *argv[]) {
FILE *fp;
static int j=0;
char line[MAX_STR_LEN],*s,tem[99];
struct listNode *head = newListNode("");
if(argc<2)
{
exit(0);
}
for(i=1;i<argc;i++)
{
fp = fopen(argv[1],"r")
if(fp==0)
{
perror(argv[i]);
continue;
}
{
while (fgets(line,MAX_STR_LEN,fp) != NULL)
{
*(strchr(line,'\n')) = '\0';
for (s = strtok(line,WS); s != NULL; s = strtok(NULL,WS))
{
insertWord(head,s);
}
}
printList(head);
fclose(fp);
}
else {
if (argc < 2) {
printf("usage: %s <filename>\n",argv[0]);
} else {
printf("%s not found.\n",argv[1]);
}
}
} return 0;
}
/*
* * newListNode: create new struct listNode
* */
struct listNode *newListNode(const char * const s) {
struct listNode *n =
(struct listNode*)malloc(sizeof(struct listNode));
n->word = (char *)malloc(sizeof(*s));
strcpy(n->word,s);
n->next = NULL;
return n;
}
/*
* * insertWord: insert given word into list in ascending order
* */
void insertWord(struct listNode *head,const char * const s) {
struct listNode *p = head,
*q = newListNode(s);
p->count=p->count+1;
while ((p->next!= NULL) &&
(strcmp(s,p->next->word) < 0))
{
p = p->next;
}
q->next = p->next;
p->next = q;
}
//要显示的单词列表C程序进行排序从文本文件的话,用链表打印他们的频率,但频率不获取计算
void printList(struct listNode *head) {
struct listNode *p = head->next;
while (p != NULL) {
printf("%5d %s\n",countlist(head),p->word);
p=p->next;
}
puts("");
}
//函数计算的频率一个字
int countlist(struct listNode *head) {
struct listNode *p = head->next;
while (p != NULL) {
if(strcmp(p->word,p->next->word)==0)
p->count=p->count+1;
p=p->next;
}
return(p->count);
}
我的程序基本上是使用链表来从多个文本文件中读取单词。按字母顺序对它们进行排序(ASCII值),然后计算每个单词的存在次数。